使用AudioRecord()录制声音

时间:2015-11-22 13:02:16

标签: android audiorecord

我使用AudioRecord录制一些音频。为了初始化AudioRecord对象,你必须提供几个参数,例如(速率,通道,编码),并且由于硬件设备支持不同的参数组合,我继续检查功能性应用程序,如

Ringdroid: Audio recording done in Ringdroid

和Rehersal助手: Audio recording in Rehersal Assistant

正如AudioRecord类的文档中所提到的,始终有效的配置是rate = 44100和channel = CHANNEL_IN_MONO。

我在初始化我的AudioRecord对象时使用相同的参数但是仍然遇到运行时错误,说我的对象未初始化。由于RingDroind在我的设备(Nexus 5)上工作正常,因此我在创建AudioObject时使用了相同的配置。

package com.example.android.visualizeaudio;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    int mSampleRate = 44100;

    Button startButton;
    boolean started = false;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startButton = (Button) this.findViewById(R.id.start_button);

    }

    private void RecordAudio() {


        int minBufferSize = AudioRecord.getMinBufferSize(
                mSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        // make sure minBufferSize can contain at least 1 second of audio (16 bits sample).
        if (minBufferSize < mSampleRate * 2) {
            minBufferSize = mSampleRate * 2;
        }
        AudioRecord audioRecord = new AudioRecord(
                MediaRecorder.AudioSource.MIC,
                mSampleRate,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                minBufferSize
        );


        audioRecord.startRecording();

        //Do some stuff here with the recorded data

        audioRecord.stop();
        audioRecord.release();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void startRec(View view) {
        if (started) {
            started = false;
            startButton.setText("Start");

        } else {
            started = true;
            startButton.setText("Stop");
            Toast.makeText(this, "Recording started", Toast.LENGTH_LONG);

            RecordAudio();
        }
    }
}

我在调试期间附加了对象检查,以防它提供更多洞察力 enter image description here

谢谢

1 个答案:

答案 0 :(得分:0)

切换到SDK目标版本22就成了伎俩。使用目标SDK 23,我遇到了这些错误。我不知道为什么,但似乎我试图访问的资源被操作系统使用。