android.media.AudioTrack#write ( )源码实例Demo

下面列出了android.media.AudioTrack#write ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: android_9.0.0_r45   文件: BlockingAudioTrack.java
private static int writeToAudioTrack(AudioTrack audioTrack, byte[] bytes) {
    if (audioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
        if (DBG) Log.d(TAG, "AudioTrack not playing, restarting : " + audioTrack.hashCode());
        audioTrack.play();
    }

    int count = 0;
    while (count < bytes.length) {
        // Note that we don't take bufferCopy.mOffset into account because
        // it is guaranteed to be 0.
        int written = audioTrack.write(bytes, count, bytes.length);
        if (written <= 0) {
            break;
        }
        count += written;
    }
    return count;
}
 
源代码2 项目: Android-Audio-Recorder   文件: Sound.java
public AudioTrack generateTrack(int sampleRate, short[] buf, int len) {
    int end = len;

    int c = 0;

    if (RawSamples.CHANNEL_CONFIG == AudioFormat.CHANNEL_IN_MONO)
        c = AudioFormat.CHANNEL_OUT_MONO;

    if (RawSamples.CHANNEL_CONFIG == AudioFormat.CHANNEL_IN_STEREO)
        c = AudioFormat.CHANNEL_OUT_STEREO;

    // old phones bug.
    // http://stackoverflow.com/questions/27602492
    //
    // with MODE_STATIC setNotificationMarkerPosition not called
    AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
            c, RawSamples.AUDIO_FORMAT,
            len * (Short.SIZE / 8), AudioTrack.MODE_STREAM);
    track.write(buf, 0, len);
    if (track.setNotificationMarkerPosition(end) != AudioTrack.SUCCESS)
        throw new RuntimeException("unable to set marker");
    return track;
}
 
源代码3 项目: Augendiagnose   文件: AudioUtil.java
/**
 * Create a sin wave of certain frequency and duration.
 *
 * @param freqHz     The frequency in Hertz
 * @param durationMs The duration in milliseconds
 * @return An AudioTrack with the corresponding sine wave.
 */
public static AudioTrack generateToneSine(final double freqHz, final int durationMs) {
	int count = (int) (BITRATE * 2.0 * (durationMs / MILLIS_IN_SECOND)) & ~1;
	short[] samples = new short[count];
	for (int i = 0; i < count; i += 2) {
		short sample = (short) (Math.sin(2 * Math.PI * i / (BITRATE / freqHz)) * 0x7FFF); // MAGIC_NUMBER
		samples[i] = sample;
		samples[i + 1] = sample;
	}
	@SuppressWarnings("deprecation")
	AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, (int) BITRATE,
			AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
			count * (Short.SIZE / 8), AudioTrack.MODE_STATIC); // MAGIC_NUMBER
	track.write(samples, 0, count);
	return track;
}
 
源代码4 项目: Augendiagnose   文件: AudioUtil.java
/**
 * Create a sin wave of certain frequency and duration.
 *
 * @param freqHz     The frequency in Hertz
 * @param durationMs The duration in milliseconds
 * @return An AudioTrack with the corresponding sine wave.
 */
public static AudioTrack generateTonePulse(final double freqHz, final int durationMs) {
	int count = (int) (BITRATE * 2.0 * (durationMs / MILLIS_IN_SECOND)) & ~1;
	short[] samples = new short[count];
	for (int i = 0; i < count; i += 2) {
		short sample = TONE_MAP_2[(int) (2 * i / (BITRATE / freqHz)) % 2];
		samples[i] = sample;
		samples[i + 1] = sample;
	}
	@SuppressWarnings("deprecation")
	AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, (int) BITRATE,
			AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
			count * (Short.SIZE / 8), AudioTrack.MODE_STATIC); // MAGIC_NUMBER
	track.write(samples, 0, count);
	return track;
}
 
源代码5 项目: Augendiagnose   文件: AudioUtil.java
/**
 * Create a tone of highest possible frequency.
 *
 * @param durationMs The duration in milliseconds
 * @return An AudioTrack with the corresponding sine wave.
 */
public static AudioTrack generateHighFreqTone(final int durationMs) {
	int count = (int) (BITRATE * 2.0 * (durationMs / MILLIS_IN_SECOND)) & ~1;
	short[] samples = new short[count];
	for (int i = 0; i < count; i += 2) { // MAGIC_NUMBER
		short sample = TONE_MAP[(i / 4) % 4]; // MAGIC_NUMBER
		samples[i] = sample;
		samples[i + 1] = sample;
	}
	@SuppressWarnings("deprecation")
	AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, (int) BITRATE,
			AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
			count * (Short.SIZE / 8), AudioTrack.MODE_STATIC); // MAGIC_NUMBER
	track.write(samples, 0, count);
	return track;
}
 
源代码6 项目: webrtc_android   文件: WebRtcAudioTrack.java
private int writeBytes(AudioTrack audioTrack, ByteBuffer byteBuffer, int sizeInBytes) {
  if (Build.VERSION.SDK_INT >= 21) {
    return audioTrack.write(byteBuffer, sizeInBytes, AudioTrack.WRITE_BLOCKING);
  } else {
    return audioTrack.write(byteBuffer.array(), byteBuffer.arrayOffset(), sizeInBytes);
  }
}
 
源代码7 项目: webrtc_android   文件: WebRtcAudioTrack.java
private int writeBytes(AudioTrack audioTrack, ByteBuffer byteBuffer, int sizeInBytes) {
  if (Build.VERSION.SDK_INT >= 21) {
    return audioTrack.write(byteBuffer, sizeInBytes, AudioTrack.WRITE_BLOCKING);
  } else {
    return audioTrack.write(byteBuffer.array(), byteBuffer.arrayOffset(), sizeInBytes);
  }
}
 
源代码8 项目: MediaSDK   文件: DefaultAudioSink.java
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
  return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
 
源代码9 项目: TelePlus-Android   文件: DefaultAudioSink.java
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
  return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
 
源代码10 项目: TelePlus-Android   文件: DefaultAudioSink.java
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
  return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
 
源代码11 项目: sample-googleassistant   文件: EmbeddedAssistant.java
@Override
public void onCompleted() {
    // create a new AudioTrack to workaround audio routing issues.
    AudioTrack audioTrack = new AudioTrack.Builder()
            .setAudioFormat(mAudioOutputFormat)
            .setBufferSizeInBytes(mAudioOutputBufferSize)
            .setTransferMode(AudioTrack.MODE_STREAM)
            .build();
    if (mAudioOutputDevice != null) {
        audioTrack.setPreferredDevice(mAudioOutputDevice);
    }
    audioTrack.setVolume(AudioTrack.getMaxVolume() * mVolume / 100.0f);
    audioTrack.play();
    mConversationHandler.post(new Runnable() {
        @Override
        public void run() {
            mConversationCallback.onResponseStarted();
        }
    });
    for (ByteBuffer audioData : mAssistantResponses) {
        final ByteBuffer buf = audioData;
        mConversationHandler.post(new Runnable() {
            @Override
            public void run() {
                mConversationCallback.onAudioSample(buf);
            }
        });
        audioTrack.write(buf, buf.remaining(),
                AudioTrack.WRITE_BLOCKING);
    }
    mAssistantResponses.clear();
    audioTrack.stop();
    audioTrack.release();

    mConversationHandler.post(new Runnable() {
        @Override
        public void run() {
            mConversationCallback.onResponseFinished();
        }
    });
    if (mMicrophoneMode == MicrophoneMode.DIALOG_FOLLOW_ON) {
        // Automatically start a new request
        startConversation();
    } else {
        // The conversation is done
        mConversationHandler.post(new Runnable() {
            @Override
            public void run() {
                mConversationCallback.onConversationFinished();
            }
        });
    }
}
 
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int writeOnLollipop(AudioTrack audioTrack, ByteBuffer byteBuffer, int sizeInBytes) {
    return audioTrack.write(byteBuffer, sizeInBytes, AudioTrack.WRITE_BLOCKING);
}
 
private int writePreLollipop(AudioTrack audioTrack, ByteBuffer byteBuffer, int sizeInBytes) {
    return audioTrack.write(byteBuffer.array(), byteBuffer.arrayOffset(), sizeInBytes);
}
 
源代码14 项目: protect-baby-monitor   文件: ListenActivity.java
private void streamAudio(final Socket socket) throws IllegalArgumentException, IllegalStateException, IOException
{
    Log.i(TAG, "Setting up stream");

    final int frequency = 11025;
    final int channelConfiguration = AudioFormat.CHANNEL_OUT_MONO;
    final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
    final int bufferSize = AudioTrack.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
    final int byteBufferSize = bufferSize*2;

    final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
            frequency,
            channelConfiguration,
            audioEncoding,
            bufferSize,
            AudioTrack.MODE_STREAM);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    final InputStream is = socket.getInputStream();
    int read = 0;

    audioTrack.play();

    try
    {
        final byte [] buffer = new byte[byteBufferSize];

        while(socket.isConnected() && read != -1 && Thread.currentThread().isInterrupted() == false)
        {
            read = is.read(buffer);

            if(read > 0)
            {
                audioTrack.write(buffer, 0, read);
            }
        }
    }
    finally
    {
        audioTrack.stop();
        socket.close();
    }
}
 
源代码15 项目: android-fskmodem   文件: MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	/// INIT FSK CONFIG
	
	try {
		mConfig = new FSKConfig(FSKConfig.SAMPLE_RATE_44100, FSKConfig.PCM_16BIT, FSKConfig.CHANNELS_MONO, FSKConfig.SOFT_MODEM_MODE_4, FSKConfig.THRESHOLD_20P);
	} catch (IOException e1) {
		e1.printStackTrace();
	}

	/// INIT FSK DECODER
	
	mDecoder = new FSKDecoder(mConfig, new FSKDecoderCallback() {
		
		@Override
		public void decoded(byte[] newData) {
			
			final String text = new String(newData);
			
			runOnUiThread(new Runnable() {
				public void run() {
					
					TextView view = ((TextView) findViewById(R.id.result));
					
					view.setText(view.getText()+text);
				}
			});
		}
	});
	
	/// INIT FSK ENCODER
	
	mEncoder = new FSKEncoder(mConfig, new FSKEncoderCallback() {
		
		@Override
		public void encoded(byte[] pcm8, short[] pcm16) {
			if (mConfig.pcmFormat == FSKConfig.PCM_8BIT) {
				//8bit buffer is populated, 16bit buffer is null
				
				mAudioTrack.write(pcm8, 0, pcm8.length);
				
				mDecoder.appendSignal(pcm8);
			}
			else if (mConfig.pcmFormat == FSKConfig.PCM_16BIT) {
				//16bit buffer is populated, 8bit buffer is null
				
				mAudioTrack.write(pcm16, 0, pcm16.length);
				
				mDecoder.appendSignal(pcm16);
			}
		}
	});
	
	///
	
	mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
			mConfig.sampleRate, AudioFormat.CHANNEL_OUT_MONO,
			AudioFormat.ENCODING_PCM_16BIT, 1024,
			AudioTrack.MODE_STREAM);
	
	mAudioTrack.play();
	
	///
	
	new Thread(mDataFeeder).start();
}
 
源代码16 项目: android-fskmodem   文件: MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	/// INIT FSK CONFIG
	
	try {
		mConfig = new FSKConfig(FSKConfig.SAMPLE_RATE_44100, FSKConfig.PCM_16BIT, FSKConfig.CHANNELS_STEREO, FSKConfig.SOFT_MODEM_MODE_4, FSKConfig.THRESHOLD_20P);
	} catch (IOException e1) {
		e1.printStackTrace();
	}

	/// INIT FSK DECODER
	
	mDecoder = new FSKDecoder(mConfig, new FSKDecoderCallback() {
		
		@Override
		public void decoded(byte[] newData) {
			
			final String text = new String(newData);
			
			runOnUiThread(new Runnable() {
				public void run() {
					
					TextView view = ((TextView) findViewById(R.id.result));
					
					view.setText(view.getText()+text);
				}
			});
		}
	});
	
	/// INIT FSK ENCODER
	
	mEncoder = new FSKEncoder(mConfig, new FSKEncoderCallback() {
		
		@Override
		public void encoded(byte[] pcm8, short[] pcm16) {
			if (mConfig.pcmFormat == FSKConfig.PCM_8BIT) {
				//8bit buffer is populated, 16bit buffer is null
				
				mAudioTrack.write(pcm8, 0, pcm8.length);
				
				mDecoder.appendSignal(pcm8);
			}
			else if (mConfig.pcmFormat == FSKConfig.PCM_16BIT) {
				//16bit buffer is populated, 8bit buffer is null
				
				mAudioTrack.write(pcm16, 0, pcm16.length);
				
				mDecoder.appendSignal(pcm16);
			}
		}
	});
	
	///
	
	mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
			mConfig.sampleRate, AudioFormat.CHANNEL_OUT_STEREO,
			AudioFormat.ENCODING_PCM_16BIT, 1024,
			AudioTrack.MODE_STREAM);
	
	mAudioTrack.play();
	
	///
	
	new Thread(mDataFeeder).start();
}
 
源代码17 项目: android-fskmodem   文件: MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	/// INIT FSK CONFIG
	
	try {
		mConfig = new FSKConfig(FSKConfig.SAMPLE_RATE_44100, FSKConfig.PCM_8BIT, FSKConfig.CHANNELS_MONO, FSKConfig.SOFT_MODEM_MODE_4, FSKConfig.THRESHOLD_20P);
	} catch (IOException e1) {
		e1.printStackTrace();
	}

	/// INIT FSK DECODER
	
	mDecoder = new FSKDecoder(mConfig, new FSKDecoderCallback() {
		
		@Override
		public void decoded(byte[] newData) {
			
			final String text = new String(newData);
			
			runOnUiThread(new Runnable() {
				public void run() {
					
					TextView view = ((TextView) findViewById(R.id.result));
					
					view.setText(view.getText()+text);
				}
			});
		}
	});
	
	/// INIT FSK ENCODER
	
	mEncoder = new FSKEncoder(mConfig, new FSKEncoderCallback() {
		
		@Override
		public void encoded(byte[] pcm8, short[] pcm16) {
			if (mConfig.pcmFormat == FSKConfig.PCM_8BIT) {
				//8bit buffer is populated, 16bit buffer is null
				
				mAudioTrack.write(pcm8, 0, pcm8.length);
				
				mDecoder.appendSignal(pcm8);
			}
			else if (mConfig.pcmFormat == FSKConfig.PCM_16BIT) {
				//16bit buffer is populated, 8bit buffer is null
				
				mAudioTrack.write(pcm16, 0, pcm16.length);
				
				mDecoder.appendSignal(pcm16);
			}
		}
	});
	
	///
	
	mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
			mConfig.sampleRate, AudioFormat.CHANNEL_OUT_MONO,
			AudioFormat.ENCODING_PCM_8BIT, 1024,
			AudioTrack.MODE_STREAM);
	
	mAudioTrack.play();
	
	///
	
	new Thread(mDataFeeder).start();
}
 
源代码18 项目: Telegram-FOSS   文件: DefaultAudioSink.java
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
  return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
 
源代码19 项目: Telegram   文件: DefaultAudioSink.java
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
  return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}