音频录制和播放环回缓冲区问题,将数据写入音轨时出现问题
Posted
技术标签:
【中文标题】音频录制和播放环回缓冲区问题,将数据写入音轨时出现问题【英文标题】:Audio Record and play loopback buffer issue, Issue while writing the data into audiotrack 【发布时间】:2012-01-10 05:32:56 【问题描述】:在这里,我尝试一次录制和播放声音,它可以正常工作几秒钟,并强制关闭在缓冲区写入音轨时显示错误(m_track.write(buffer,0,BUF_SIZE);)。 请检查以下代码,并建议我是否正确初始化音轨对象。
int SAMPLE_RATE = 8000;
int BUF_SIZE = 1024;
byte[] buffer = new byte[BUF_SIZE];
function()
try
buffersize = AudioRecord
.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
catch (Throwable t)
Log.e("Audio", "Buffer size failed");
if (buffersize <= BUF_SIZE)
buffersize = BUF_SIZE;
try
m_record = new AudioRecord(MediaRecorder.Audiosource.MIC,
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, buffersize * 2);
m_track = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, buffersize * 2,
AudioTrack.MODE_STREAM);
m_track.setPlaybackRate(SAMPLE_RATE);
catch (Throwable t)
Log.e("Audio", "Audio Failed");
m_record.startRecording();
m_track.play();
try
m_thread = new Runnable()
public void run()
while (m_isRun)
m_record.read(buffer, 0, BUF_SIZE);
m_track.write(buffer, 0, BUF_SIZE);
;
m_thread.run();
catch (Exception e)
Log.e("ERROR", "exception: " + e.getLocalizedMessage());
Log.i("D2Record", "loopback exit");
【问题讨论】:
你是怎么解决这个问题的?我也遇到了同样的问题...请帮助***.com/questions/9413998/… 【参考方案1】:我对这个主题并不十分熟悉,但我认为您在缓冲区大小方面遇到了问题。我将大部分代码放在一边,主要专注于缓冲区处理。
int SAMPLE_RATE = 8000;
int BUF_SIZE = 1024;
int buffersize = AudioRecord
.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
bufferSize = Math.Max(bufferSize, AudioTrack
.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
bufferSize = Math.max(bufferSize, BUF_SIZE);
byte[] buffer = new byte[bufferSize];
m_record = new AudioRecord(MediaRecorder.AudioSource.MIC,
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);
m_track = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize,
AudioTrack.MODE_STREAM);
m_track.setPlaybackRate(SAMPLE_RATE);
m_record.startRecording();
m_track.play();
while (m_isRun)
// You should check 'read' for errors after read.
int read = m_record.read(buffer, 0, bufferSize);
// You should check 'wrote' for errors after write.
int wrote = m_track.write(buffer, 0, read);
【讨论】:
以上是关于音频录制和播放环回缓冲区问题,将数据写入音轨时出现问题的主要内容,如果未能解决你的问题,请参考以下文章
Swift AVAssetWriter 将带有麦克风音频和设备音频的视频录制成带有一个音轨 AVAssetTrack 的视频