为什么mediaRecorder在尝试录制语音时未能做好准备

时间:2015-09-04 06:39:01

标签: java android mediarecorder android-mediarecorder

我正在尝试使用媒体录制器录制语音。 现在我创建了新的媒体记录器然后我尝试使用准备并开始无济于事,我总是收到以下错误:

09-04 09:27:36.335: E/MediaRecorder(26320): prepare failed: -17
09-04 09:27:36.335: W/System.err(26320): java.io.IOException: prepare failed.
09-04 09:27:36.350: W/System.err(26320):    at android.media.MediaRecorder._prepare(Native Method)
09-04 09:27:36.350: W/System.err(26320):    at android.media.MediaRecorder.prepare(MediaRecorder.java:595)
09-04 09:27:36.350: W/System.err(26320):    at com.abg.quickies.AudioRecorder.start(AudioRecorder.java:57)
09-04 09:27:36.350: W/System.err(26320):    at com.abg.quickies.ServiceFloatingButton.recordCall(ServiceFloatingButton.java:321)
09-04 09:27:36.350: W/System.err(26320):    at com.abg.quickies.ServiceFloatingButton.handlePressAction(ServiceFloatingButton.java:254)
09-04 09:27:36.350: W/System.err(26320):    at com.abg.quickies.ServiceFloatingButton.access$1(ServiceFloatingButton.java:217)
09-04 09:27:36.350: W/System.err(26320):    at com.abg.quickies.ServiceFloatingButton$1.onTouch(ServiceFloatingButton.java:173)
09-04 09:27:36.350: W/System.err(26320):    at android.view.View.dispatchTouchEvent(View.java:3934)
09-04 09:27:36.355: W/System.err(26320):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903)
09-04 09:27:36.355: W/System.err(26320):    at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2218)
09-04 09:27:36.355: W/System.err(26320):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1889)
09-04 09:27:36.360: W/System.err(26320):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 09:27:36.360: W/System.err(26320):    at android.os.Looper.loop(Looper.java:123)
09-04 09:27:36.360: W/System.err(26320):    at android.app.ActivityThread.main(ActivityThread.java:3691)
09-04 09:27:36.360: W/System.err(26320):    at java.lang.reflect.Method.invokeNative(Native Method)
09-04 09:27:36.365: W/System.err(26320):    at java.lang.reflect.Method.invoke(Method.java:507)
09-04 09:27:36.365: W/System.err(26320):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
09-04 09:27:36.365: W/System.err(26320):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
09-04 09:27:36.370: W/System.err(26320):    at dalvik.system.NativeStart.main(Native Method)

代码如下:

private void recordCall() 
{

    Parameters params=getMyApplication().get_parameters();
    Date date=new Date();
    SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    String fileName=formater.format(date);
    String path=params.getRecordsPath()+fileName;

    //record 
    set_recorder(new AudioRecorder(path));

    try {
        get_recorder().start();
        set_isRecording(true);
        showRecorderNotification();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}

录音机:

public class AudioRecorder {

  final MediaRecorder recorder = new MediaRecorder();
  final String path;
  private int _audioSource; 

  /**
   * Creates a new audio recording at the given path (relative to root of SD card).
   * default audio source is voicecall
   */
  public AudioRecorder(String path) {
    this.path = sanitizePath(path);
    set_audioSource(MediaRecorder.AudioSource.VOICE_CALL);

  }

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

  /**
   * Starts a new recording.
   */
  public void start() throws IOException {
    Log.i("GABI", "AudioRecorder- start()");

    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(get_audioSource());
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(path);
    recorder.prepare();
    recorder.start();
  }

  /**
   * Stops a recording that has been previously started.
   */
  public void stop() throws IOException {
    Log.i("GABI", "AudioRecorder- stop()");
    recorder.stop();
    recorder.reset();
    recorder.release();
  }

public int get_audioSource() {
    return _audioSource;
}

public void set_audioSource(int _audioSource) {
    this._audioSource = _audioSource;
}

}

为什么会这样?

1 个答案:

答案 0 :(得分:0)

尝试将VOICE_CALL更改为MIC。此外,如果它不起作用,您可以检查这部分代码。经过测试和运作。

/*
 * The application needs to have the permission to write to external storage
 * if the output file is written to the external storage, and also the
 * permission to record audio. These permissions must be set in the
 * application's AndroidManifest.xml file, with something like:
 *
 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 * <uses-permission android:name="android.permission.RECORD_AUDIO" />
 *
 */
package com.android.audiorecordtest;

import android.app.Activity;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;

import java.io.IOException;


public class AudioRecordTest extends Activity
{
    private static final String LOG_TAG = "AudioRecordTest";
    private static String mFileName = null;

    private RecordButton mRecordButton = null;
    private MediaRecorder mRecorder = null;

    private PlayButton   mPlayButton = null;
    private MediaPlayer   mPlayer = null;

    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

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

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

    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();
    }

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

    class RecordButton extends Button {
        boolean mStartRecording = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };

        public RecordButton(Context ctx) {
            super(ctx);
            setText("Start recording");
            setOnClickListener(clicker);
        }
    }

    class PlayButton extends Button {
        boolean mStartPlaying = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onPlay(mStartPlaying);
                if (mStartPlaying) {
                    setText("Stop playing");
                } else {
                    setText("Start playing");
                }
                mStartPlaying = !mStartPlaying;
            }
        };

        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }
    }

    public AudioRecordTest() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/audiorecordtest.3gp";
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout ll = new LinearLayout(this);
        mRecordButton = new RecordButton(this);
        ll.addView(mRecordButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        mPlayButton = new PlayButton(this);
        ll.addView(mPlayButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        setContentView(ll);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}