MediaRecorder录制音频及代码的抽取封装

1、背景

android提供了MediaRecorder类,通过MediaRecorder录制音频的过程很简单,按步骤进行即可;在很多开发项目中,我们见到代码的封装很好;常常感觉这才是大牛写出的代码,其实我们也是可以写出来的,今天就通过一个MediaRecorder录制音频的实例,进行代码的抽取实现封装;

2、MediaRecorder录制音频的步骤(来自疯狂Androud讲义)

1:创建MediaRecorder对象;
2:调用MediaRecorder对象的setAudioSource()方法设置声音来源,一般传入MediaRecorder.AudioSource.MIC参数,指定录制来自麦克风的声音;
3:调用MediaRecorder对象的setOutputFormat()设置所录制的音频文件的格式;
4:调用MediaRecorder对象的setAudioEncoder()、setAudioEncodingBitRate(int bitRate)、setAudioSamplingRate(int samplingRate)设置所录制的声音的编码格式、编码位率、采样率等;这些参数将控制所录制音频的频率,文件的大小;一般来说,声音品质越好,文件越大;
5:调用MediaRedorder的setOutputFile(String path)方法,设置录制的音频文件的保存位置;
6:调用MediaRecorder的prepare()方法,准备录制;
7:调用MdiaRecorder的start()方法,开始录制;
8:录制完成,调用MediaRecorder对象的stop()方法停止录制,并调用release()方法释放资源;

注意:上面的第3 和第4 两个步骤,千万不能搞反;否则程序将会抛出 IllegalStateException 异常;

3、MediaPlayer的状态图

我们参考MediaRecorder的状态图就可以明白MediaRecorder录制音频的步骤:
这里写图片描述

4、实例代码:

没抽取MediaRecorder之前的代码:

1、布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <Button
        android:id="@+id/openRecord" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open Record"
        android:textSize="20sp"
        />
    <Button 
        android:id="@+id/closeRecord"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Close Record"
        android:textSize="20sp"
        />
    <Button 
        android:id="@+id/playSound"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play Sound"
        android:textSize="20sp"
        />
    <Button 
        android:id="@+id/stopSound"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Sound"
        android:textSize="20sp"
        />
</LinearLayout>

四个按钮作用分别是:开始录制音频、停止录制音频、开始播放音频、停止播放音频

2、MainActivity代码:
public class MyActivity extends Activity implements OnClickListener{

    private Button bt_start;
    private Button bt_stop;
    private Button bt_play;
    private Button bt_stopSound;
    private MediaRecorder mRecorder;
    private MediaPlayer mPlayer;
    private File soundFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        bt_start = (Button) this.findViewById(R.id.openRecord);
        bt_stop = (Button) this.findViewById(R.id.closeRecord);
        bt_play = (Button) this.findViewById(R.id.playSound);
        bt_stopSound = (Button) this.findViewById(R.id.stopSound);
        bt_start.setOnClickListener(this);
        bt_stop.setOnClickListener(this);
        bt_play.setOnClickListener(this);
        bt_stopSound.setOnClickListener(this);
        bt_play.setEnabled(false);
        bt_stopSound.setEnabled(false);

        mRecorder = new MediaRecorder();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.openRecord:
            startRecord();
            break;
        case R.id.closeRecord:
            stopRecord();
            break;
        case R.id.playSound:
            playSound();
            break;
        case R.id.stopSound:
            stopSound();
            break;
        default:

            break;
        }
    }

    private void stopSound() {
        if(mPlayer.isPlaying()){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }

    private void stopRecord() {
        if(null != mRecorder){
            mRecorder.stop();
            mRecorder.release();
            bt_play.setEnabled(true);
            bt_stopSound.setEnabled(true);
        }
    }

    private void playSound() {
        if(soundFile != null && soundFile.exists()){
            try {
                mPlayer = new MediaPlayer();
                mPlayer.reset();
                mPlayer.setDataSource(soundFile.getAbsolutePath());
                mPlayer.prepare();
                mPlayer.start();
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    }

    private void startRecord() {
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //Toast.makeText(MainActivity.this, "SD卡不存在,请插入SD卡!", Toast.LENGTH_LONG).show();
            return;
        }
        try {
            //创建保存录制音频的文件
            soundFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile(),"/sound.amr");
            mRecorder.reset();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setOutputFile(soundFile.getAbsolutePath());
            mRecorder.prepare();
            mRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        if(null != mRecorder){
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
        if(mPlayer != null){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
        super.onDestroy();
    }
}

在上面的MainActivity代码中,我们可以看到虽然我们对代码进行了很好的模块化,但感觉如果我们把MediaRecorder 重新封装,MainActivity的代码量会更简介;好了,现在我们就开始通过自定义一个MyMediaRecorder来封装MediaRecorder,在MainActivity中我们只需通过MyMediaRecorder的封装来调用MediaRecorder,可以简化MainActivity中的代码量;

3、MediaRecorder的封装
public class MyMediaRecorder {
    private MediaRecorder mRecorder;
    private Context context;
    public MyMediaRecorder(Context context){
        mRecorder = new MediaRecorder();
        this.context = context;
    }

    public void startRecord(File soundFile){
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(context, "SD卡不存在,请插入SD卡!", Toast.LENGTH_LONG).show();
            return;
        }
        try {
            mRecorder.reset();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setOutputFile(soundFile.getAbsolutePath());
            mRecorder.prepare();
            mRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopRecord(){
        if(null != mRecorder){
            mRecorder.stop();
            mRecorder.release();
        }
    }

    public void onDestroy(){
        if(null != mRecorder){
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
    }
}
4、MediaPlayer的封装

同样我们也可以把MediaPlayer进行封装:

public class MyMediaPlayer {
    private MediaPlayer mPlayer;

    public MyMediaPlayer(){
        mPlayer = new MediaPlayer();
    }

    public void playSound(File soundFile){
        try {
            mPlayer.reset();
            mPlayer.setDataSource(soundFile.getAbsolutePath());
            mPlayer.prepare();
            mPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

    public void stopSound(){
        if(mPlayer.isPlaying()){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }

    public void onDestroy(){
        if(mPlayer != null){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }
}
5、封装之后的MainActivity 代码:
public class MyActivity02 extends Activity implements OnClickListener{

    private Button bt_start;
    private Button bt_stop;
    private Button bt_play;
    private Button bt_stopSound;
    private MyMediaRecorder myMediaRecorder;
    private MyMediaPlayer myMediaPlayer;
    private File soundFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        bt_start = (Button) this.findViewById(R.id.openRecord);
        bt_stop = (Button) this.findViewById(R.id.closeRecord);
        bt_play = (Button) this.findViewById(R.id.playSound);
        bt_stopSound = (Button) this.findViewById(R.id.stopSound);
        bt_start.setOnClickListener(this);
        bt_stop.setOnClickListener(this);
        bt_play.setOnClickListener(this);
        bt_stopSound.setOnClickListener(this);
        bt_play.setEnabled(false);
        bt_stopSound.setEnabled(false);

        //myMediaRecorder = new MyMediaRecorder(MainActivity.this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.openRecord:
            startRecord();
            break;
        case R.id.closeRecord:
            stopRecord();
            break;
        case R.id.playSound:
            playSound();
            break;
        case R.id.stopSound:
            stopSound();
            break;
        default:

            break;
        }
    }

    public void stopSound() {
        myMediaPlayer.stopSound();
    }


    public void playSound() {
        if(soundFile != null && soundFile.exists()){
            myMediaPlayer = new MyMediaPlayer();
            myMediaPlayer.playSound(soundFile);
        }
    }

    public void stopRecord() {
        myMediaRecorder.stopRecord();
        bt_play.setEnabled(true);
        bt_stopSound.setEnabled(true);
    }

    public void startRecord() {
        try {
            soundFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile(),"/sound.amr");
            if(soundFile != null && soundFile.exists()){
                myMediaRecorder.startRecord(soundFile);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void onDestroy() {
        myMediaRecorder.onDestroy();
        myMediaPlayer.onDestroy();
    }
}

现在,我们在MainActivity中只需要通过封装好的MyMediaRecorder、MyMediaPlayer可以实现音频的录制;复杂的代码都被我们封装起来了,所以在我们的MainActivity中,代码看上去更精炼;

现在我们看一下我们的MainActivity 还能更进一步封装吗?
其实代码的封装就是把有共性的给抽取出来,放到另一个类中;现在我们可以看到在我们的MainActivity中,各种视图控件看上去占据了大部分代码量,很繁琐;由于视图控件是一个界面,主要是与用户进行交互的;看到他们的共性点,所以我们也是可以进行抽取的;

6、MainActivity的进一步抽取视图控件

我把所有在MainActivity中出现的视图控件,去不都抽取到MyManager中:

public class MyManager implements OnClickListener{
    private Button bt_start;
    private Button bt_stop;
    private Button bt_play;
    private Button bt_stopSound;
    private MyMediaRecorder myMediaRecorder;
    private MyMediaPlayer myMediaPlayer;
    private File soundFile;
    private MainActivity context;

    public MyManager(Context context){
        this.context = (MainActivity) context;
    }

    public void initView(){
        bt_start = (Button) context.findViewById(R.id.openRecord);
        bt_stop = (Button) context.findViewById(R.id.closeRecord);
        bt_play = (Button) context.findViewById(R.id.playSound);
        bt_stopSound = (Button) context.findViewById(R.id.stopSound);
        bt_start.setOnClickListener(this);
        bt_stop.setOnClickListener(this);
        bt_play.setOnClickListener(this);
        bt_stopSound.setOnClickListener(this);
        bt_play.setEnabled(false);
        bt_stopSound.setEnabled(false);

        myMediaRecorder = new MyMediaRecorder(context);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.openRecord:
            startRecord();
            break;
        case R.id.closeRecord:
            stopRecord();
            break;
        case R.id.playSound:
            playSound();
            break;
        case R.id.stopSound:
            stopSound();
            break;
        default:

            break;
        }
    }

    public void stopSound() {
        myMediaPlayer.stopSound();
    }


    public void playSound() {
        if(soundFile != null && soundFile.exists()){
            myMediaPlayer = new MyMediaPlayer();
            myMediaPlayer.playSound(soundFile);
        }
    }

    public void stopRecord() {
        myMediaRecorder.stopRecord();
        bt_play.setEnabled(true);
        bt_stopSound.setEnabled(true);
    }

    public void startRecord() {
        try {
            soundFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile(),"/sound.amr");
            if(soundFile != null && soundFile.exists()){
                myMediaRecorder.startRecord(soundFile);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void onDestroy() {
        myMediaRecorder.onDestroy();
        myMediaPlayer.onDestroy();
    }
}

现在让我们再看一下MainActivity 的代码:

public class MainActivity extends Activity {

    private MyManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        manager = new MyManager(MainActivity.this);
        manager.initView();
    }

    @Override
    protected void onDestroy() {
        manager.onDestroy();
    }

}

是不是很惊讶,简简单单的4行代码;对!!!这就是抽取、封装的重要性,它能把我们的代码进行提炼,让代码更精炼,更方便阅读;

好的,以下是一个简单的录制 WAV 音频文件的示例代码: ```java import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class AudioRecorder { private static final String TAG = "AudioRecorder"; private static final int SAMPLE_RATE_IN_HZ = 44100; private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO; private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT; private AudioRecord audioRecord; private boolean isRecording; public void startRecording() { int minBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT); audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT, minBufferSize); isRecording = true; audioRecord.startRecording(); new Thread(new Runnable() { @Override public void run() { writeDataToFile(); } }).start(); } public void stopRecording() { isRecording = false; audioRecord.stop(); audioRecord.release(); } private void writeDataToFile() { byte[] buffer = new byte[1024]; String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.wav"; File file = new File(filename); if (file.exists()) { file.delete(); } try { FileOutputStream fos = new FileOutputStream(file); while (isRecording) { int read = audioRecord.read(buffer, 0, buffer.length); fos.write(buffer, 0, read); } fos.close(); } catch (IOException e) { Log.e(TAG, "writeDataToFile: ", e); } } } ``` 将上述代码保存到名为 `AudioRecorder.java` 的文件中,然后在你的 Android 项目中引入该文件。 在你的 Activity 或 Fragment 中,你可以通过以下方法来使用上述代码: ```java private AudioRecorder audioRecorder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); audioRecorder = new AudioRecorder(); } public void startRecording(View view) { audioRecorder.startRecording(); } public void stopRecording(View view) { audioRecorder.stopRecording(); } ``` 这里我们假设你在布局文件中创建了两个按钮,分别用于启动和停止录制。在 `startRecording()` 方法中,我们创建了一个新的线程来执行音频数据写入文件的操作。在 `stopRecording()` 方法中,我们停止录制并释放相关资源。 请注意,上述代码中的文件路径是 `/sdcard/recording.wav`。如果你的设备没有 SD 卡或者你的应用程序没有 SD 卡写入权限,那么你需要修改文件路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值