Android开发(17) 录音和播放音频

2020-03-16 15:09:55 浏览数 (1)

需求

使用android手机录音

了解MediaRecorder

代码语言:javascript复制
 mRecorder = new MediaRecorder();

mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(newFileName());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
    mRecorder.prepare();
} catch (IOException e) {
    Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();

步骤

  1. 设定声音来源。这里指定为 麦克风
  2. 指定输出格式 。
  3. 指定输出文件。
  4. 指定音频编码格式。
  5. 预备。
  6. 启动录音。

代码

配合启动录音的过程,就会有终止录音的过程,代码:

mRecorder.stop();

mRecorder.release(); mRecorder = null; 结束,并释放资源。

播放

录音完成后,总得要听听吧。我们看播放的过程:

代码语言:javascript复制
mPlayer = new MediaPlayer();

try {
    mPlayer.setDataSource(fileName);
    mPlayer.prepare();
    mPlayer.start();
} catch (IOException e) {
    Log.e(LOG_TAG, "prepare() failed");
}

终止播放呢

代码语言:javascript复制
 mPlayer.release();
 mPlayer = null;

完整代码

代码语言:javascript复制
class SoundRecorder {   
MediaRecorder mRecorder;

    boolean isRecording;

    public void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(newFileName());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
        mRecorder.start();

    }

    public void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }

    public String newFileName() {
        String mFileName = Environment.getExternalStorageDirectory()
                .getAbsolutePath();

        String s = new SimpleDateFormat("yyyy-MM-dd hhmmss")
                .format(new Date());
        return mFileName  = "/rcd_"   s   ".3gp";
    }
}


 

  public class SoundPlayer {  
    MediaPlayer mPlayer;


    public void startPlaying(String fileName) {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(fileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    public void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }
}

0 人点赞