private class wPlaySound extends Thread {
@Override
public void run() {
float sampleRate = 8000;
int sampleSizeInBytes = 2;
int samplePerFrame = (int) sampleRate / (1000 / 20); // 20мс
int frameSize = sampleSizeInBytes * samplePerFrame;
int minBuf = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
Log.v("w201", "Buffer Size: " + minBuf);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBuf * 100, AudioTrack.MODE_STREAM);
at.setStereoVolume(1.0f,1.0f);
at.play();
for (int i = 0; i < position; i = i + frameSize) {
Log.v("w201","write: "+at.write(data, i, frameSize));
}
at.flush();
at.stop();
at.release();
}
}
我能听懂是否听到噪音或声音不正确。但我什么也没听到......
编辑: 我是如何得到数据的。它并不完美,不适用于所有设备,但它可以在我的手机和平板电脑上运行
private class wRecordSound extends Thread {
public boolean stop = false;
public wRecordSound() {
position = 0;
}
@Override
public void run() {
int freq = 8000;
int sampleSizeInBytes = 2;
int samplePerFrame = (int) freq / (1000 / 20); // 20мс
int frameSize = sampleSizeInBytes * samplePerFrame;
final int bufferSize = AudioRecord.getMinBufferSize(freq,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
final AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, freq,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);
if (audioRecord.getState()!=AudioRecord.STATE_INITIALIZED) {
Log.v("w201","audio recorder not init" );
return;
}
try {
audioRecord.startRecording();
while (!stop) {
position += audioRecord.read(data, position, frameSize);
}
} catch (Exception e) {
e.printStackTrace();
}
audioRecord.stop();
audioRecord.release();
}
}
EDIT2:我发现只有在我调用AudioTrack的方法停止后才开始播放声音。但是,如果我需要播放每一帧,我该怎么做?
_loop_
_receive_frame_
at.play
at.write(_one frame_)
at.stop
答案 0 :(得分:0)
以下代码:
at.play();
at.write(data, i, frameSize));
at.flush();
at.stop();
at.release();
将无法正确播放。仅将块写入,直到将数据写入缓冲区为止,直到完成播放为止。您需要删除“ flush”,无论如何不应在播放缓冲区中调用它。见下文:
at.play();
at.write(data, i, frameSize));
at.stop();
at.release();
这样,停止将完成播放。但是,如果您需要立即停止,则应该执行以下操作:
at.pause();
at.flush();