Android的Audiorecord不起作用

时间:2012-10-31 17:09:54

标签: java android audio recording audiorecord

我尝试在Android中实现一个简单的录音机。使用MediaRecorder非常容易,但对于我的范围,我需要AudioRecord,因为我要用jTrasform转换输入数据。 但我无法初始化Audiorecorder。 这是我的代码,我用findAudioRecord()方法尝试所有组合来创建记录器(CHANNEL,SAMPLE RATE ......)。 他们中没有人工作。 希望你的帮助

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioSource;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class FFTActivity extends Activity {

  private TextView textView1;
  private TextView textView2;

  private static final int RECORDSTATE_RECORDING = 3;
  private static final int RECORDER_BPP = 16;
  private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav";
  private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
  private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
  private static final int RECORDER_SAMPLERATE = 44100;
  private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
  private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

  private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };


  private int bufferSize = 0;
  private AudioRecord recorder = null;

  private int cont;

  int cont2 = 0;
  int contENCODING = 0;
  int contCHANNEL = 0;

  String s ="";



  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      textView1 = (TextView) findViewById(R.id.testo1);
      textView2 = (TextView) findViewById(R.id.testo2);

      bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);

      recorder = findAudioRecord();



}

  public AudioRecord findAudioRecord() {
        for (int rate : mSampleRates) {

            for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
                for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
                    try {
                        int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);

                        if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
                            // check if we can instantiate and have a success
                            AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate, channelConfig, audioFormat, (bufferSize*2));
                            textView2.setText("NOT ERROR_BAD_VALUE    "+mSampleRates[cont2] +"  "+ bufferSize);

                            if (recorder.getState() == AudioRecord.STATE_INITIALIZED){

                                textView2.setText("getState(): "+recorder.getState()+"   getMinBufferSize(): "+AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING));

                                return recorder;
                            }    
                        }
                    } catch (Exception e) {
                        textView2.setText("ECCEZZIONE"+e);
                    }
                    contCHANNEL++;
                }
                contENCODING++;
            }
            cont2++;  
        }
        textView1.setText("NON INIZIALIZZATO " + contCHANNEL + "   " + contENCODING); 
        return null;
    } 

2 个答案:

答案 0 :(得分:0)

点击此链接:http://www.devlper.com/2010/12/android-audio-recording-part-2/。此外,还有一个示例应用程序来记录本教程中的音频。

一旦你做对了就很简单了!

答案 1 :(得分:-1)

试试这个工作代码...............

活动类代码:

public class SoundRecordingActivity extends Activity {

  MediaRecorder recorder;
  File audiofile = null;
  private static final String TAG = "SoundRecordingActivity";
  private View startButton;
  private View stopButton;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startButton = findViewById(R.id.start);
    stopButton = findViewById(R.id.stop);
  }

  public void startRecording(View view) throws IOException {

    startButton.setEnabled(false);
    stopButton.setEnabled(true);

    File sampleDir = Environment.getExternalStorageDirectory();
    try {
      audiofile = File.createTempFile("sound", ".3gp", sampleDir);
    } catch (IOException e) {
      Log.e(TAG, "sdcard access error");
      return;
    }
    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();
  }

  public void stopRecording(View view) {
    startButton.setEnabled(true);
    stopButton.setEnabled(false);
    recorder.stop();
    recorder.release();
    addRecordingToMediaLibrary();
  }

  protected 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 base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Uri newUri = contentResolver.insert(base, values);

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
    Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
  }
} 

main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Recording"
        android:onClick="startRecording" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Recording" 
        android:enabled="false"
         android:onClick="stopRecording"
        />

</LinearLayout> 

在AndroidManifest.xml中添加权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.RECORD_AUDIO" />