2011-12-01 95 views
2

Ham在我的項目中進行錄音。問題是在我的項目中得到運行時異常。RuntimeException:音頻錄製開始失敗

12-02 14:58:47.145: E/AndroidRuntime(22802): FATAL EXCEPTION: main 
12-02 14:58:47.145: E/AndroidRuntime(22802): java.lang.RuntimeException: start failed. 
12-02 14:58:47.145: E/AndroidRuntime(22802): at android.media.MediaRecorder.start(Native Method) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at com.android.audio.AudioRecordActivity.startRecording(AudioRecordActivity.java:80) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at com.android.audio.AudioRecordActivity.access$1(AudioRecordActivity.java:67) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at com.android.audio.AudioRecordActivity$3.onClick(AudioRecordActivity.java:138) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at android.view.View.performClick(View.java:3460) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at android.view.View$PerformClick.run(View.java:13955) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at android.os.Handler.handleCallback(Handler.java:605) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at android.os.Handler.dispatchMessage(Handler.java:92) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at android.os.Looper.loop(Looper.java:137) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at android.app.ActivityThread.main(ActivityThread.java:4340) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at java.lang.reflect.Method.invokeNative(Native Method) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at java.lang.reflect.Method.invoke(Method.java:511) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
12-02 14:58:47.145: E/AndroidRuntime(22802): at dalvik.system.NativeStart.main(Native Method) 

當我調試,我得到錯誤的代碼這一行:

recorder.start();

我的源代碼如下

package com.android.audio; 

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

import org.apache.http.util.ByteArrayBuffer; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.ContentValues; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.media.MediaRecorder; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.provider.MediaStore; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 

public class AudioRecordActivity extends Activity 
{ 
    private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp"; 
    private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4"; 
    private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder"; 
    File file; 
    private MediaRecorder recorder = null; 
    private int currentFormat = 0; 
    private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP }; 
    private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP }; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    setButtonHandlers(); 
    enableButtons(false); 
    setFormatButtonCaption(); 
} 

    private void setButtonHandlers() { 
      ((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick); 
    ((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick); 
    ((Button)findViewById(R.id.btnFormat)).setOnClickListener(btnClick); 
    } 

    private void enableButton(int id,boolean isEnable){ 
      ((Button)findViewById(id)).setEnabled(isEnable); 
    } 

    private void enableButtons(boolean isRecording) { 
      enableButton(R.id.btnStart,!isRecording); 
      enableButton(R.id.btnFormat,!isRecording); 
      enableButton(R.id.btnStop,isRecording); 
    } 

    private void setFormatButtonCaption(){ 
      ((Button)findViewById(R.id.btnFormat)).setText(getString(R.string.audio_format) + " (" + file_exts[currentFormat] + ")"); 
    } 

    private String getFilename(){ 

      String filepath = Environment.getExternalStorageDirectory().getPath(); 
      file = new File(filepath,AUDIO_RECORDER_FOLDER); 

      if(!file.exists()){ 
        file.mkdirs(); 
      } 




      return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]); 
    } 


    private void startRecording(){ 
      recorder = new MediaRecorder(); 

      recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 
      recorder.setOutputFormat(output_formats[currentFormat]); 
      recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 
      recorder.setOutputFile(getFilename()); 

      recorder.setOnErrorListener(errorListener); 
      recorder.setOnInfoListener(infoListener); 

      try { 
        recorder.prepare(); 
        recorder.start(); 
      } catch (IllegalStateException e) { 
        e.printStackTrace(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 

    private void stopRecording(){ 
      if(null != recorder){ 
        recorder.stop(); 
        recorder.reset(); 
        recorder.release(); 

        recorder = null; 
      } 
    } 

    private void displayFormatDialog(){ 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      String formats[] = {"MPEG 4", "3GPP"}; 

      builder.setTitle(getString(R.string.choose_format_title)) 
         .setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() { 

          @Override 
          public void onClick(DialogInterface dialog, int which) { 
            currentFormat = which; 
            setFormatButtonCaption(); 

            dialog.dismiss(); 
          } 
         }) 
         .show(); 
    } 

    private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() { 
      @Override 
      public void onError(MediaRecorder mr, int what, int extra) { 
        AppLog.logString("Error: " + what + ", " + extra); 
      } 
    }; 

    private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() { 
      @Override 
      public void onInfo(MediaRecorder mr, int what, int extra) { 
        AppLog.logString("Warning: " + what + ", " + extra); 
      } 
    }; 

private View.OnClickListener btnClick = new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        switch(v.getId()){ 
          case R.id.btnStart:{ 
            AppLog.logString("Start Recording"); 

            enableButtons(true); 
            startRecording(); 

            break; 
          } 
          case R.id.btnStop:{ 
            AppLog.logString("Start Recording"); 

            enableButtons(false); 
            stopRecording(); 

            break; 
          } 
          case R.id.btnFormat:{ 
            displayFormatDialog(); 

            break; 
          } 
        } 
      } 
    }; 


} 
+0

你是否提供了權限 –

+0

ya謝謝我忘記了權限。我添加了此權限,現在它的工作<使用權限android:name =「android.permission.RECORD_AUDIO」/> – pratibha

+0

對不起,這是行不通的。 – pratibha

回答

7

如您需要設置以下權限在AndroidManifest.xml中文件android developer documentation描述:

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

如果設置這些,它不應該拋出這個例外。評論後

編輯:如果你得到一個mRecorder.prepare();異常FileNotFound,我想這是因爲你在mPlayer.setDataSource(mFileName);引用該文件不存在,或不正確初始化。也許如果你嘗試記錄文件名字符串,你可以看看它是否看起來像你想要的樣子。

+0

只是錯過了:) – Tobbe

+0

plz幫我找出什麼是火腿越來越非法的狀態,即使我添加權限 – pratibha

+0

mRecorder.prepare();火腿在調試後得到錯誤,並得到filenotfound異常 – pratibha

0

使用這些權限:

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

,你可能會得到解決, 必須添加WRITE_EXTERNAL_STORAGE許可。

0
VideoPlayerActivity extends Activity { 
    /** Called when the activity is first created. */ 

    MediaPlayer mp; 

    File mPath; 
    String datavideo = "/sdcard/musicfiles.mp4"; 
    String datamusic = "/sdcard/musicfileone.mp3"; 

    String urlString = "http://192.168.1.92/Stream/song.mp3"; 

    String urlVodeo = "http://192.168.1.92/Stream/Wildlife.mp4"; 

    Button btnVideo, btnAudio, btnViewVideo; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     btnVideo = (Button) findViewById(R.id.btnStoreVideo); 
     btnAudio = (Button) findViewById(R.id.btnstoreAudio); 
     btnViewVideo = (Button) findViewById(R.id.btnViewVideo); 
     btnVideo.setOnClickListener(new OnClickListener() { 

      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 

       try { 

        setDataSourc(datavideo); 

       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 
     }); 
     btnAudio.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       try { 

        setDataSource(datamusic); 

       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 
     }); 

     btnViewVideo.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       Intent intent = new Intent(VideoPlayerActivity.this, 
         PlayingVideo.class); 
       startActivity(intent); 
      } 
     }); 
    } 

    private void setDataSource(String path) throws IOException { 

     // HttpClient client = new DefaultHttpClient(); 
     // HttpPost post = new HttpPost(urlString); 
     // HttpResponse response = client.execute(post); 
     // HttpEntity cn = response.getEntity(); 

     URL url = new URL(urlString); 
     URLConnection cn = url.openConnection(); 
     cn.connect(); 

     InputStream stream = cn.getInputStream();// getContent(); 
     if (stream == null) { 
      throw new RuntimeException("stream is null"); 
     } 
     mPath = new File(datamusic); 
     mPath.createNewFile(); 
     FileOutputStream out = new FileOutputStream(mPath); 
     byte buf[] = new byte[128]; 
     do { 
      int numRead = stream.read(buf); 
      if (numRead <= 0) { 
       break; 
      } 
      out.write(buf, 0, numRead); 
     } while (true); 
     mp = new MediaPlayer(); 
     mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
     try { 
      mp.setDataSource(path); 
      mp.prepare(); 
      mp.start(); 

     } catch (Exception e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
     } 
     try { 
      stream.close(); 
     } catch (Exception ex) { 
      String sDummy = ex.toString(); 
      System.out.println("hello dummy" + sDummy); 

     } 
    } 

    private void setDataSourc(String path) throws IOException { 

     // HttpClient client = new DefaultHttpClient(); 
     // HttpPost post = new HttpPost(urlString); 
     // HttpResponse response = client.execute(post); 
     // HttpEntity cn = response.getEntity(); 

     URL url = new URL(urlVodeo); 
     URLConnection cn = url.openConnection(); 
     cn.connect(); 

     InputStream stream = cn.getInputStream();// getContent(); 
     if (stream == null) { 
      throw new RuntimeException("stream is null"); 
     } 
     mPath = new File(datavideo); 
     mPath.createNewFile(); 
     FileOutputStream out = new FileOutputStream(mPath); 
     byte buf[] = new byte[128]; 
     do { 
      int numRead = stream.read(buf); 
      if (numRead <= 0) { 
       break; 
      } 
      out.write(buf, 0, numRead); 
     } while (true); 
     // mp = new MediaPlayer(); 
     // mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
     try { 
      // mp.setDataSource(path); 
      // mp.prepare(); 
      // mp.start(); 

     } catch (Exception e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
     } 
     try { 
      stream.close(); 
     } catch (Exception ex) { 
      String sDummy = ex.toString(); 
      System.out.println("hello dummy" + sDummy); 

     } 
    } 

} 

我用上面的代碼在我的應用程序來解決問題,這可能會幫助你。

1

我所用:

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

,它給我的錯誤。 後來我把它改爲:

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

看起來愚蠢的,但意外的是爲我工作。