如何在Android中使用AudioRecorder

时间:2012-10-09 07:45:20

标签: android audio-recording

我正在创建一个应用程序,我想要集成音频录制功能和输出文件,我必须使用 .mp3 格式。请提供一些我可以学习的好教程。

提前致谢...

3 个答案:

答案 0 :(得分:1)

尝试以下方法:

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Environment;

public class AudioRecorder {

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

    public AudioRecorder(String path) {
        this.path = sanitizePath(path);
    }

    private String sanitizePath(String path) {
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        if (!path.contains(".")) {
            path += ".3gp";
        }
        return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
    }

    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 + ".");
        }

        File directory = new File(path).getParentFile();
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IOException("Path to file could not be created.");
        }

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

    public void stop() throws IOException {
        recorder.stop();
        recorder.release();
    }
}

答案 1 :(得分:0)

答案 2 :(得分:0)

这是执行此操作的简单代码。

    MediaRecorder mediarecorder = new MediaRecorder();
    mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mediarecorder.setOutputFile("/sdcard/myv.mp3");
    try {
        mediarecorder.prepare();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mediarecorder.start();