媒体记录中的Android illegalstateexception

时间:2013-05-27 11:44:57

标签: android android-emulator

我正在使用记录媒体。在以下代码中,有2个按钮,一个用于开始记录,另一个用于停止记录。一旦我运行代码,就会发生illegalStateException但是给定名称的文件存储在emulator的sd卡上。后面是代码:

    package com.example.try_music;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
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;
import android.widget.Toast;

public class MainActivity extends Activity {

private Button btnStart;
private Button btnStop;

File audioFile = null;
MediaRecorder recorder;

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

    btnStart = (Button)findViewById(R.id.btnStart);
    btnStop = (Button)findViewById(R.id.btnStop);

}

public void startRecording(View view) throws IllegalStateException, IOException
{
    btnStart.setEnabled(false);
    btnStop.setEnabled(true);

    File fileSample = Environment.getExternalStorageDirectory();
    try {
        audioFile = File.createTempFile("my_sound", ".3gp", fileSample);
    } catch (IOException e) {           
        Log.e("myerrortag", "sdcard access error");
    }

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
    recorder.setOutputFile(audioFile.getAbsolutePath());
    recorder.reset();
    recorder.prepare();
    recorder.start();
}
public void stopRecording(View view)
{
    btnStart.setEnabled(true);
    btnStop.setEnabled(false);
    recorder.stop();
    recorder.release();
    addRecordingToMediaLibrary();
}

public void addRecordingToMediaLibrary() {
    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());
    ContentResolver contentResolver = getContentResolver();

    Uri uriBase = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Uri newUri  = contentResolver.insert(uriBase, values);

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
    Toast.makeText(getApplicationContext(), "added file", Toast.LENGTH_SHORT).show();       
}

}

以下是logcat条目:

05-27 16:50:49.453: E/AndroidRuntime(23804): java.lang.IllegalStateException: Could not execute method of the activity

我添加了所有必要的权限。任何帮助将受到高度赞赏。提前谢谢。

0 个答案:

没有答案