Android:需要录制麦克风input

有没有一种方法来录制麦克风的input,而它正在进行实时回放/预览? 我试图使用AudioRecord和AudioTrack来做到这一点,但问题是,我的设备无法播放录制的audio文件。 实际上,任何android播放器应用程序都无法播放录制的audio文件。

另一方面,使用Media.Recorderlogging会生成一个可以被任何播放器应用程序播放的良好录制的audio文件。 但事实上,我无法实时录制麦克风input时进行预览/回放。

任何反馈非常感谢! 提前致谢!

要(几乎)实时录制和播放audio,您可以启动一个单独的线程并使用AudioRecordAudioTrack

只要小心反馈。 如果扬声器在设备上响起的声音足够大,则反馈可能会非常快。

 /* * Thread to manage live recording/playback of voice input from the device's microphone. */ 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); track = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10, AudioTrack.MODE_STREAM); recorder.startRecording(); track.play(); /* * 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 = buffers[ix++ % buffers.length]; N = recorder.read(buffer,0,buffer.length); track.write(buffer, 0, buffer.length); } } catch(Throwable x) { Log.w("Audio", "Error reading voice audio", x); } /* * Frees the thread's resources after the loop completes so that it can be run again */ finally { recorder.stop(); recorder.release(); track.stop(); track.release(); } } /** * Called from outside of the thread in order to stop the recording/playback loop */ private void close() { stopped = true; } } 

编辑

audio不是真的logging到一个文件。 AudioRecord对象将audio编码为16位PCM数据并将其放置在缓冲区中。 然后, AudioTrack对象从缓冲区读取数据并通过扬声器播放。 SD卡上没有可供您稍后访问的文件。

您不能同时读取和写入SD卡上的文件以实时播放/预览,因此您必须使用缓冲区。

清单中的权限需要正常工作:

 <uses-permission android:name="android.permission.RECORD_AUDIO" ></uses-permission> 

另外,2d缓冲区数组不是必需的。 代码的逻辑即使只有一个缓冲区也是有效的,如下所示:

 short[] buffer = new short[160]; while (!stopped) { //Log.i("Map", "Writing new data to buffer"); int n = recorder.read(buffer, 0, buffer.length); track.write(buffer, 0, n); }