试图从Android手机上的麦克风录音

时间:2016-07-06 06:57:18

标签: android android-audiorecord

我正在尝试从麦克风录制,我通过尝试一些代码片段来构建代码,但没有任何反应: 这是代码,有人可以告诉我如何使这个工作。我是Android编码的新手。

package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.util.Log;
import java.io.*;  
import android.os.Environment;

public class MainActivity extends Activity {
    public static final int SAMPLING_RATE = 44100;
    public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
    public static final int CHANNEL_IN_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    public static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLING_RATE, CHANNEL_IN_CONFIG, AUDIO_FORMAT);
    public static final String AUDIO_RECORDING_FILE_NAME = "recording.raw";
    private static final String LOGTAG = "MyActivity";
    private volatile boolean mStop = true;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView text = new TextView(this);
        text.setText("Hello World, Ranjan");
        setContentView(text);
    }

    /*public void run() 
    {

        TextView text = new TextView(this);
        text.setText(" hello smart mute");

    }*/
    //@Override
    public void run() {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
        Log.v(LOGTAG, "Starting recording…");

        byte audioData[] = new byte[BUFFER_SIZE];
        AudioRecord recorder = new AudioRecord(AUDIO_SOURCE,
                    SAMPLING_RATE, CHANNEL_IN_CONFIG,
                    AUDIO_FORMAT, BUFFER_SIZE);
        recorder.startRecording();

        String filePath = Environment.getExternalStorageDirectory().getPath()
                    + "/" + AUDIO_RECORDING_FILE_NAME;
        BufferedOutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(filePath));
        } catch (FileNotFoundException e) {
            Log.e(LOGTAG, "File not found for recording ", e);
        }

        while (!mStop) {
            int status = recorder.read(audioData, 0, audioData.length);

            if (status == AudioRecord.ERROR_INVALID_OPERATION ||
                status == AudioRecord.ERROR_BAD_VALUE) {
                Log.e(LOGTAG, "Error reading audio data!");
                return;
            }

            try {
                os.write(audioData, 0, audioData.length);
            } catch (IOException e) {
                Log.e(LOGTAG, "Error saving recording ", e);
                return;
            }
        }

        try {
            os.close();

            recorder.stop();
            recorder.release();

            Log.v(LOGTAG, "Recording done…");
            mStop = false;

        } catch (IOException e) {
            Log.e(LOGTAG, "Error when releasing", e);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将这些添加到您的清单文件

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

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

尝试下面的代码,它可以帮助我们录制,停止和播放音频

public class MainActivity extends Activity {
Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  play=(Button)findViewById(R.id.button3);
  stop=(Button)findViewById(R.id.button2);
  record=(Button)findViewById(R.id.button);

  stop.setEnabled(false);
  play.setEnabled(false);
  outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;

  myAudioRecorder=new MediaRecorder();
  myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
  myAudioRecorder.setOutputFile(outputFile);

  record.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        try {
           myAudioRecorder.prepare();
           myAudioRecorder.start();
        }

        catch (IllegalStateException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

        catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

        record.setEnabled(false);
        stop.setEnabled(true);

        Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
     }
  });

  stop.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        myAudioRecorder.stop();
        myAudioRecorder.release();
        myAudioRecorder  = null;

        stop.setEnabled(false);
        play.setEnabled(true);

        Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
     }
  });

  play.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
        MediaPlayer m = new MediaPlayer();

        try {
           m.setDataSource(outputFile);
        }

        catch (IOException e) {
           e.printStackTrace();
        }

        try {
           m.prepare();
        }

        catch (IOException e) {
           e.printStackTrace();
        }

        m.start();
        Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
     }
  });
}