【发布时间】:2013-05-14 14:39:57
【问题描述】:
我正在尝试从 MIC 直接录制到一个短阵列。
目标不是将音轨写入文件,而是将其保存在一个短数组中。
如果尝试了几种方法,我发现最好的方法是使用 AudioRecord 录制并使用 AudioTrack 播放。我在这里找到了一个很好的课程:
Android: Need to record mic input
这个类满足了我的所有需求,我只需要修改它就可以达到我想要的结果,但是......我不太懂,我错过了一些东西......
这是我的修改(根本不起作用):
private class Audio extends Thread {
private boolean stopped = false;
/**
* Give the thread high priority so that it's not canceled unexpectedly, and start it
*/
private Audio()
{
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
start();
}
@Override
public void run()
{
Log.i("Audio", "Running Audio Thread");
AudioRecord recorder = null;
AudioTrack track = null;
//short[][] buffers = new short[256][160];
int ix = 0;
/*
* Initialize buffer to hold continuously recorded audio data, start recording, and start
* playback.
*/
try
{
int N = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
recorder = new AudioRecord(AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10);
short[] buff = new short[N];
recorder.startRecording();
/*
* Loops until something outside of this thread stops it.
* Reads the data from the recorder and writes it to the audio track for playback.
*/
while(!stopped) {
//Log.i("Map", "Writing new data to buffer");
//short[] buffer = buffer[ix++ % buffer.length];
N = recorder.read(buff, 0, buff.length);
}
recorder.stop();
recorder.release();
track = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10, AudioTrack.MODE_STREAM);
track.play();
for (int i =0; i< buff.length;i++) {
track.write(buff, i, buff.length);
}
} catch(Exception x) {
//Log.e("Audio", x.getMessage());
x.printStackTrace();
} finally {
track.stop();
track.release();
}
}
/**
* Called from outside of the thread in order to stop the recording/playback loop
*/
private void close()
{
stopped = true;
}
}
我需要在短数组缓冲区中录制声音,当用户按下按钮时,播放它......但是现在,我正在尝试录制声音,当用户按下按钮时,录制停止,声音开始播放...
谁能帮帮我?
谢谢。
【问题讨论】:
-
你在'recorder.read()'函数调用中得到了什么吗?它在“N”中返回多少字节?你知道当你像这样读取缓冲区时,你得到的音频片段非常小吗?这就像 20 毫秒的数据,所以如果您尝试通过聆听进行验证,您将听不到它。您的循环继续读入单个缓冲区,直到 'stopped' 设置为 true。所以你只会播放最后一段音频。
-
N 返回(在我按下停止按钮的那一刻)4096。说实话,我不太了解这段代码,可能是因为我没有太多使用输入流...谢谢你的解释,现在我明白为什么很多次听起来都是一样的 bip...那么我怎么能把所有字节都保存在短数组中呢?
标签: android audio-recording bytebuffer