java.lang.RuntimeException:setAudioSource失败

时间:2016-05-18 05:10:19

标签: android android-studio

我是Android开发的新手。我只是想用6.0.1 Marshmallow设备用android studio(2.1.1)测试录制音频。

public class MainActivity extends AppCompatActivity {

    Button start, stop;
    public MediaRecorder recorder = null;
    public String fileextn = ".mp4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        start = (Button) findViewById(R.id.start_button);
        stop = (Button) findViewById(R.id.stop_button);

        start.setOnClickListener(new View.OnClickListener(){

                                     @Override
                                     public void onClick(View v) {

                                         switch (v.getId()) {
                                             case R.id.start_button:
                                                 startRecord();
                                             case R.id.stop_button:
                                                 stoprecord();
                                         }
                                     }

                                 }
        );

    }

    public void startRecord() {
        recorder = new MediaRecorder();
        recorder.reset();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setOutputFile(getFilePath());

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

    public void stoprecord() {

        if (recorder != null) {
            recorder.stop();
            recorder.reset();

            recorder.release();
            recorder = null;
        }

    }


    private String getFilePath() {

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

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

        return (file.getAbsolutePath() + "/" + fileextn);
    }


}

顺便说一下,我在manifext.xml文件中包含了uses-permission。

这是我在Android监视器中获得的内容:

  05-18 11:08:36.576 10414-10414/com.example.gk.audiocapture E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.gk.audiocapture, PID: 10414
                                                                         java.lang.RuntimeException: stop failed.
                                                                             at android.media.MediaRecorder.stop(Native Method)
                                                                             at com.example.gk.audiocapture.MainActivity.stoprecord(MainActivity.java:65)
                                                                             at com.example.gk.audiocapture.MainActivity$1.onClick(MainActivity.java:35)
                                                                             at android.view.View.performClick(View.java:5207)
                                                                             at android.view.View$PerformClick.run(View.java:21168)
                                                                             at android.os.Handler.handleCallback(Handler.java:746)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

我尝试了一些答案,没找到任何答案。

我的AndroidManifest.xml:

   <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gk.audiocapture">
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

8 个答案:

答案 0 :(得分:31)

我遇到了完全相同的问题并设法通过请求录制音频的权限来修复它:

                        if (ActivityCompat.checkSelfPermission(activity(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {

                        ActivityCompat.requestPermissions(activity(), new String[]{Manifest.permission.RECORD_AUDIO},
                                BuildDev.RECORD_AUDIO);

                    } else {
                        startRecording();
                    }

其中

BuildDev.RECORD_AUDIO是public static final int RECORD_AUDIO = 0;

答案 1 :(得分:4)

我很困惑你的标题是java.lang.RuntimeException: setAudioSource failed,你的堆栈跟踪显示java.lang.RuntimeException: stop failed.

对于java.lang.RuntimeException: setAudioSource failed,您可能缺少运行时权限。

您需要从用户处获取Manifest.permission.RECORD_AUDIO

public void onRecordBtnClicked() {
  if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
      != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.RECORD_AUDIO },
        10);
  } else {
    recordAudio();
  }
}

private void recordAudio() {
  //Record Audio.
}

@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
    @NonNull int[] grantResults) {
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  if (requestCode == 10) {
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      recordAudio();
    }else{
      //User denied Permission.
    }
  }
}

答案 2 :(得分:1)

您在from main_project.main_project.libs.exceptions import ( APIException400, APIException405, APIException403, exception_handler_dispatcher, ) s中遗漏了一些var2=$(echo $myvar | wc -c)

break

答案 3 :(得分:0)

试试这段代码

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.record_btn:
            recordAudio();
            break;
        case R.id.play_pause_btn:
            playAudio();
            break;
    }
}

private void playAudio() {
    if (mPlaying) {
        record_btn.setEnabled(false);
        startPlaying();
        play_pause_btn.setText("Stop Playing");
        mPlaying = false;
    } else {
        stopPlaying();
        play_pause_btn.setText("Start Playing");
        mPlaying = true;
        record_btn.setEnabled(true);
    }
}

private void startPlaying() {
    mAudioPlayer = new MediaPlayer();
    try {
        mAudioPlayer.setDataSource(mFilename);
        mAudioPlayer.prepare();
        updatingPlyingProgressBar();
        mAudioPlayer.start();
        showProgressforPlaying();

    } catch (IOException e) {
        e.printStackTrace();
    }
    mAudioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            playAudio();
        }
    });
}

private void updatingPlyingProgressBar() {
    long maxTime = mAudioPlayer.getDuration();
    int second = (int) maxTime / 1000;
    playing_audio_progressBar.setMax(second * 1000);
    playing_audio_progressBar.setProgress(0);
    playing_audio_max_time.setText(second > 9 ? "00:" + second : "00:0" + second);
}

private void stopPlaying() {
    mAudioPlayer.stop();
    mAudioPlayer.release();
    mPlayingTimer.cancel();
    mAudioPlayer = null;
}

private void showProgressforPlaying() {
    seconds = 0;
    mPlayingTimer = new Timer();
    mPlayingTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (!mPlaying) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (playing_audio_progressBar.getProgress() < mAudioPlayer.getDuration()) {
                            playing_audio_progressBar.setProgress(playing_audio_progressBar.getProgress() + 1000);
                            seconds++;
                            playing_audio_time.setText(seconds > 9 ? "00:" + seconds : "00:0" + seconds);
                        } else {
                            playAudio();
                        }
                    }
                });
            }
        }
    }, 1000, 1000);
}

private void recordAudio() {
    if (mRecording) {
        play_pause_btn.setEnabled(false);
        mRecording = false;
        audio_recording_progressBar.setMax(MAXTIME);
        audio_recording_progressBar.setProgress(0);
        startRecording();
        showProgressforRecording();
        record_btn.setText("Stop");

    } else {
        stopRecording();
        record_btn.setText("Record");
        mRecording = true;
        mRecordingtimer.cancel();
        play_pause_btn.setEnabled(true);
    }
}

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

}

private void startRecording() {
    mAudioRecorder = new MediaRecorder();
    mFilename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AudioRecordDemo/" + "Audio" + System.currentTimeMillis() + ".3gp";

    mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mAudioRecorder.setOutputFile(mFilename);
    mAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    try {
        mAudioRecorder.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mAudioRecorder.start();
}

private void showProgressforRecording() {
    seconds = 0;
    mRecordingtimer = new Timer();
    mRecordingtimer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (!mRecording) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (audio_recording_progressBar.getProgress() < MAXTIME) {
                            audio_recording_progressBar.setProgress(audio_recording_progressBar.getProgress() + 1000);
                            seconds++;
                            recorded_audio_time.setText(seconds > 9 ? "00:" + seconds : "00:0" + seconds);
                        } else {
                            recordAudio();
                        }
                    }
                });
            }
        }
    }, 1000, 1000);
}

答案 4 :(得分:0)

的startRecording

 public void startRecording(View view) throws IOException {  
      startButton.setEnabled(false);  
      stopButton.setEnabled(true);  
          //Creating file  
      File dir = Environment.getExternalStorageDirectory();  
      try {  
        audiofile = File.createTempFile("sound", ".3gp", dir);  
      } catch (IOException e) {  
        Log.e(TAG, "external storage access error");  
        return;  
      }  
          //Creating MediaRecorder and specifying audio source, output format, encoder & output format  
      recorder = new MediaRecorder();  
      recorder.setAudioSource(MediaRecorder.AudioSource.MIC);  
      recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);  
      recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);  
      recorder.setOutputFile(audiofile.getAbsolutePath());  
      recorder.prepare();  
      recorder.start();  
    }  

stopRecording

 public void stopRecording(View view) {  
      startButton.setEnabled(true);  
      stopButton.setEnabled(false);  
          //stopping recorder  
      recorder.stop();  
      recorder.release();  
         //after stopping the recorder, create the sound file and add it to media library.  
      addRecordingToMediaLibrary();  
    }  

AddtoLib

   protected void addRecordingToMediaLibrary() {  
          //creating content values of size 4  
      ContentValues values = new ContentValues(4);  
      long current = System.currentTimeMillis();  
      values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());  
      values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));  
      values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");  
      values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());  

           //creating content resolver and storing it in the external content uri  
      ContentResolver contentResolver = getContentResolver();  
      Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
      Uri newUri = contentResolver.insert(base, values);  

         //sending broadcast message to scan the media file so that it can be available  
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));  
      Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();  
    } 

答案 5 :(得分:0)

您可以使用此方法解决问题。

    @RequiresApi(api = Build.VERSION_CODES.M)
public void getPermissionToRecordAudio() {
    // 1) Use the support library version ContextCompat.checkSelfPermission(...) to avoid
    // checking the build version since Context.checkSelfPermission(...) 
    // 2) Always check for permission (even if permission has already been granted)
    // since the user can revoke permissions at any time through Settings
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {

        // The permission is NOT already granted.
        // Check if the user has been asked about this permission already and denied
        // it. If so, we want to give more explanation about why the permission is needed.
        // Fire off an async request to actually get the permission
        // This will show the standard permission request dialog UI
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                RECORD_AUDIO_REQUEST_CODE);

    }
}

答案 6 :(得分:0)

查询:错误setaudiosource failed

答案:按照说明进行操作。 如果您使用的是棉花糖及以上版本,请在AndroidMainfest.xml中声明权限,然后按照以下几行进行操作。

requestPermissions(new String[]{
                                    Manifest.permission_group.STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.CAMERA,
                                    Manifest.permission.RECORD_AUDIO,
}                           `enter code here`

答案 7 :(得分:-2)

试试这个。希望它可以帮到你

change 

recorder.setAudioSource(1);

to

recorder.setAudioSource(MediaRecorder.AudioSource.MIC); in your startRecord method.