在SGS2上的Android 2.3.4中的麦克风录制音频

时间:2012-03-06 18:27:57

标签: java android audio

您好我有这个类用于录制来自麦克风的音频流

import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

public class AudioRecorder {

final MediaRecorder recorder = new MediaRecorder();
public 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
                + ".");
    }

    // make sure the directory we plan to store the recording in exists
    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);
    try {
        recorder.prepare();
    } catch (Exception e) {
        Log.e("Error: recorder - ",e.toString());
    }
    recorder.start();
}

public void stop() throws IOException {

    recorder.stop();
    recorder.release();

}

public void playarcoding(String path) throws IOException {
    MediaPlayer mp = new MediaPlayer();
    mp.setDataSource(path);
    mp.prepare();
    mp.start();
    mp.setVolume(10, 10);
}

}

在我的活动中我像这样使用它

AudioRecorder ar = new AudioRecorder("/sdcard/a.3gp");
     if(addButton.getText() != "running"){
         try { 
            ar.start();
        } catch (Exception e) {
            Log.d("Error:",e.toString());
        }
        addButton.setText("running");
     }
     else{
         try {
            ar.stop();
        } catch (Exception e) {
            Log.d("Error:",e.toString());
        }
     }

我也放了这个权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>

我按下活动按钮后,我认为它开始记录 问题是我试图阻止它... 当我再次按下按钮停止它时会出现此错误:

stop called in an invalid state: 1
java.lang.IllegalStateException

任何人都可以解释为什么会发生这种情况以及我如何解决这个问题,因为我用Google搜索 因为它并没有找到解决方案。

这发生在录音机的停止功能中。

0 个答案:

没有答案