0

我正在研究记录媒体。在以下代码中,有 2 个按钮,一个用于开始记录,另一个用于停止记录。我一运行代码,就发生了非法状态异常,但是具有给定名称的文件存储在 emulator.following 的 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

我已经添加了所有必要的权限。任何帮助将不胜感激。提前致谢。

4

0 回答 0