Android进阶篇录音

/**
 * @author gongchaobin
 * 
 * Media录音类
 */
public class AudioRecoder {
    private static final String TAG = AudioRecoder.class.getSimpleName();
    
    private MediaRecorder mRecorder;
    private MediaPlayer mPlayer;
    
    public static AudioRecoder instance;

    private AudioRecoder() {
        super();
    }

    public static AudioRecoder getInstance() {
        if (instance == null) {
            synchronized (AudioRecoder.class) {
                if (instance == null) {
                    instance = new AudioRecoder();
                }
            }
        }
        return instance;
    }
    
    /**开始播放
     * @param path 音频文件存储路径
     * @return
     */
    public void startPlaying(String path) {
        Log.info(TAG, "---------recoder playing---------");
        
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(path);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.error(TAG, "prepare() failed");
        }
    }
    
    /**停止播放*/
    public void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }
    
    /**开始录音
     * @param path 录音存储的路径
     * @return
     */
    public void startRecording(String path) {
        Log.info(TAG, "path= " + path);
        
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(path);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.error(TAG, "prepare() failed");
        }
        mRecorder.start();
    }
    
    /**停止录音*/
    public void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }
}
原文地址:https://www.cnblogs.com/gongcb/p/2729240.html