我目前正在尝试为Android构建一个放大器。目标是记录和回放同时记录的内容。我创建了一个可以解决这个问题的线程。然而,声音变得不稳定。这是我试过的。
private class RecordAndPlay extends Thread{
int bufferSize;
AudioRecord aRecord;
short[] buffer;
public RecordAndPlay() {
bufferSize = AudioRecord.getMinBufferSize(22050, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
buffer = new short[bufferSize];
}
@Override
public void run() {
aRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 22050, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
try {
aRecord.startRecording();
} catch (Exception e) {
}
int bufferedResult = aRecord.read(buffer,0,bufferSize);
final AudioTrack aTrack = new AudioTrack(AudioManager.STREAM_MUSIC, samplingRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferedResult, AudioTrack.MODE_STREAM);
aTrack.setNotificationMarkerPosition(bufferedResult);
aTrack.setPlaybackPositionUpdateListener(new OnPlaybackPositionUpdateListener() {
@Override
public void onPeriodicNotification(AudioTrack track) {
// TODO Auto-generated method stub
}
@Override
public void onMarkerReached(AudioTrack track) {
Log.d("Marker reached", "...");
aTrack.release();
aRecord.release();
run();
}
});
aTrack.play();
aTrack.write(buffer, 0, buffer.length);
}
public void cancel(){
aRecord.stop();
aRecord.release();
}
}
答案 0 :(得分:0)
您的播放不稳定,因为AudioTrack正在挨饿而且没有顺利获取数据。在您的代码中,您递归地调用run并为每个标记创建一个新的AudioTrack。相反,只将AudioRecord和AudioTrack实例化一次并处理它们的事件。此外,为了帮助平滑播放,您可能应该在播放前稍微开始录制并保留录制缓冲区的队列。然后,您可以管理将这些缓冲区传递给AudioTrack,并确保始终在每个标记事件上提交一个新的缓冲区。