0

我目前正在尝试为 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();

    }
}
4

1 回答 1

0

您的播放断断续续,因为 AudioTrack 正在挨饿并且无法顺利获取数据。在您的代码中,您递归调用 run 并为每个标记创建一个新的 AudioTrack。相反,只实例化一次 AudioRecord 和 AudioTrack 并处理它们的事件。此外,为了帮助平滑播放,您可能应该在播放之前稍微开始录制并维护已录制缓冲区的队列。然后,您可以管理将这些缓冲区传递给 AudioTrack,并确保在每个标记事件上始终有一个新缓冲区要提交。

于 2013-08-07T22:57:32.920 回答