如何从Android中的Media Recorder获取音频流

时间:2019-12-14 14:39:36

标签: android audio audio-streaming

我想在Android中制作流式音频记录器。我不确定如何获取音频流以及如何设置音频流的缓冲区大小。

下面是我的媒体记录器课程

public class MyMediaRecorder {

    final MediaRecorder recorder = new MediaRecorder();
    final File path;

    /**
     * Creates a new audio recording at the given path (relative to root of SD
     * card).
     */
    public MyMediaRecorder(File path) {
        this.path = path;
    }



    /**
     * Starts a new recording.
     */
    public void start() throws IOException {
        String state = android.os.Environment.getExternalStorageState();
        if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
            throw new IOException("SD Card is not mounted.  It is " + state
                    + ".");
        }

        // make sure the directory we plan to store the recording in exists


        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(path.getAbsolutePath());
        recorder.prepare();
        recorder.start();
    }

    /**
     * Stops a recording that has been previously started.
     */
    public void stop() throws IOException {
        recorder.stop();
        recorder.release();
    }
}

在开始记录时,我需要获取缓冲区大小并将其发送到服务器并行记录音频。我应该使用Media Recorder的音频记录和音频曲目吗?请建议我该怎么做

1 个答案:

答案 0 :(得分:1)

您应该使用AudioRecord。 这是一个简单的代码,显示了如何使用AudioRecord类。

final int sampleRate = 48000;
final int channelConfig = AudioFormat.CHANNEL_IN_MONO;
final int audioFormat = AudioFormat.ENCODING_PCM_16BIT;

int minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
AudioRecord microphone = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, minBufferSize * 10);

microphone.startRecording();

//Since audioformat is 16 bit, we need to create a 16 bit (short data type) buffer
short[] buffer = new short[1024];

while(!stopped) {

    int readSize = microphone.read(buffer, 0, buffer.length);
    sendDataToServer(buffer, readSize);

}

microphone.stop();
microphone.release();

如果需要实时音频记录器和流媒体,则应谨慎对待性能,并尽可能快地读取所有数据并进行管理以将其发送到服务器。 Github中有很多项目,您可以重用它们并从他们的想法中学习。我在这里分享其中一些(特别是录音机类),但是您可以搜索并找到更多。
1. AudioRecorder
2. FullDuplexNetworkAudioCallService
3. MicRecorder