下面列出了android.media.AudioTrack#write ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
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);
}
}
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);
}
}
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
@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);
}
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();
}
}
@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();
}
@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();
}
@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();
}
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}
@TargetApi(21)
private static int writeNonBlockingV21(AudioTrack audioTrack, ByteBuffer buffer, int size) {
return audioTrack.write(buffer, size, WRITE_NON_BLOCKING);
}