0

目前,我正在尝试在 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();
}

}
4

1 回答 1

2

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

目前,这应该会有所帮助:

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

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

于 2013-04-26T12:20:45.597 回答