android中录音的示例项目

时间:2011-08-25 10:00:38

标签: java android audio-recording

  

可能重复:
  Audio Recording

嗨我是android领域的新开发者,我把程序写入android中的audio recordig,bt现在还没有工作,我想为我的小应用程序记录人声,所以请给出示例项目来开发我的应用程序

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码示例来录制音频

public class AudioRecorder extends Activity {

    private ImageButton button;
    private ImageButton stopbutton;
    private MediaRecorder mediarecorder;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audiorecorderlayout);

        button = (ImageButton)findViewById(R.id.record);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                record("/sdcard/audiorecordexample.3gpp");
            }
        });

        stopbutton = (ImageButton)findViewById(R.id.stop);
        stopbutton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopRecord();
            }
        });
    }

    private void record(String filePath) {
        try {

            File mediafile = new File(filePath);

            if (mediafile.exists()) {
                mediafile.delete();
            }
            mediafile = null;

            // record button goes away
            button.setVisibility(View.GONE);

            // stop button shows up
            stopbutton.setVisibility(View.VISIBLE);

            // set up media recorder
            if (mediarecorder == null)
                mediarecorder = new MediaRecorder();
            mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mediarecorder.setOutputFile(filePath)

            // prepare media recorder
            mediarecorder.prepare();

            // start media recorder
            mediarecorder.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopRecord() {

        // stop media recorder
        mediarecorder.stop();

        // reset media recorder
        mediarecorder.reset();

        // record button shows up
        button.setVisibility(View.VISIBLE);

        // stop button goes away
        stopbutton.setVisibility(View.GONE);

    }
}