录音机的未处理异常类型IOException

时间:2013-04-26 05:52:17

标签: java android audio

目前,我正在尝试在Android应用程序中开发录音机,最终发送到在线服务器,然后进行多播。但是在我继续之前,我遇到了像Unhandled exception type IOException这样的错误。我在错误出现的部分添加了**符号。请帮忙。

package com.example.testproject;

import java.io.File;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;

public class Sound extends Activity {

private MediaPlayer mediaPlayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;


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

    OUTPUT_FILE=Environment.getExternalStorageDirectory()+"/audiorecorder.3gpp";

}

public void buttonTapped(View view){

    switch(view.getId()){
    case R.id.btnstart:

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

    break;

    case R.id.btnfinish:

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

    break;

    case R.id.btnplay:

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

    break;

    case R.id.btnstop:

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

    break;
    }       

}

private void stopPlayback(){

}

private void playRecording() throws Exception{
    ditchMediaPlayer();
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setDataSource(OUTPUT_FILE);
    mediaPlayer.prepare();
    mediaPlayer.start();

}

private void ditchMediaPlayer(){
    if(mediaPlayer != null)
    {
        try{
            mediaPlayer.release();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

private void stopRecording(){

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

}

private void beginRecording(){

    ditchMediaRecorder();
    File outputFile = new File(OUTPUT_FILE);

    if(outputFile.exists())
        outputFile.delete();

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(OUTPUT_FILE);
    **recorder.prepare();**
    recorder.start();

}

private void ditchMediaRecorder() { 
    if(recorder != null)
        recorder.release();
}

}

1 个答案:

答案 0 :(得分:1)

您必须处理调用recorder.prepare()时可能发生的IO错误。有关异常处理的更多信息,请参阅the official Java docs

目前,这应该有所帮助:

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

但请确保在发布应用程序之前实施正确的错误处理。