在 android 工作室中通过录音机检测语音

Detect voice by audio recorder in android studio

好吧,我想实现一个功能,比如当应用程序启动时,录音机会开始录音,当用户保持沉默时,直到用户说话才会发生任何事情。然后,它会保存用户语音的PCM文件,然后停止录音。

Voice Detection in Android Application

上面是我找到的和我的问题类似的问题,但是这个link的答案不行。而且我不知道如何修改它,因为我不了解代码的概念。

请帮帮我~

嗯,我解决了我的问题,这是我的解决方案。 我修改了来自这个url的代码: Voice Detection in Android Application

private static final String TAG = "MainActivity";


private static int RECORDER_SAMPLERATE = 44100;
private static int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
private static int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

private Button btn, btn_convert, btn_play;
private TextView txv;

boolean isRecording = false;
private File file;
private AudioRecord audioRecord;
int bufferSizeInBytes = 0;
Context context = MainActivity.this;

// path
final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/final.pcm" ;
final String outpath = path.replace(".pcm", ".wav");

public void autoRecording(){
    // Get the minimum buffer size required for the successful creation of an AudioRecord object.
    bufferSizeInBytes = AudioRecord.getMinBufferSize( RECORDER_SAMPLERATE,
            RECORDER_CHANNELS,
            RECORDER_AUDIO_ENCODING
    );
    // Initialize Audio Recorder.
    AudioRecord audioRecorder = new AudioRecord( MediaRecorder.AudioSource.MIC,
            RECORDER_SAMPLERATE,
            RECORDER_CHANNELS,
            RECORDER_AUDIO_ENCODING,
            bufferSizeInBytes
    );
    // Start Recording.
    txv.setText("Ing");
    audioRecorder.startRecording();
    isRecording = true;

    // for auto stop
    int numberOfReadBytes   = 0;
    byte audioBuffer[]      = new  byte[bufferSizeInBytes];
    boolean recording       = false;
    float tempFloatBuffer[] = new float[3];
    int tempIndex           = 0;

    // create file

    file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/final.pcm");
    Log.d(TAG, "recording: file path:" + file.toString());

    if (file.exists()){
        Log.d(TAG,"file exist, delete file");
        file.delete();
    }
    try {
        Log.d(TAG,"file created");
        file.createNewFile();
    } catch (IOException e) {
        Log.d(TAG,"didn't create the file:" + e.getMessage());
        throw new IllegalStateException("did not create file:" + file.toString());
    }

    // initiate media scan and put the new things into the path array to
    // make the scanner aware of the location and the files you want to see
    MediaScannerConnection.scanFile(context, new String[] {file.toString()}, null, null);

    // output stream
    OutputStream os = null;
    DataOutputStream dos = null;
    try {
        os = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        dos = new DataOutputStream(bos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


    // While data come from microphone.
    while( true )
    {
        float totalAbsValue = 0.0f;
        short sample        = 0;

        numberOfReadBytes = audioRecorder.read( audioBuffer, 0, bufferSizeInBytes );

        // Analyze Sound.
        for( int i=0; i<bufferSizeInBytes; i+=2 )
        {
            sample = (short)( (audioBuffer[i]) | audioBuffer[i + 1] << 8 );
            totalAbsValue += (float)Math.abs( sample ) / ((float)numberOfReadBytes/(float)2);
        }

        // read in file
        for (int i = 0; i < numberOfReadBytes; i++) {
            try {
                dos.writeByte(audioBuffer[i]);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Analyze temp buffer.
        tempFloatBuffer[tempIndex%3] = totalAbsValue;
        float temp                   = 0.0f;
        for( int i=0; i<3; ++i )
            temp += tempFloatBuffer[i];

        if( (temp >=0 && temp <= 2100) && recording == false )  // the best number for close to device: 3000
        {                                                       // the best number for a little bit distance : 2100
            Log.i("TAG", "1");
            tempIndex++;
            continue;
        }

        if( temp > 2100 && recording == false )
        {
            Log.i("TAG", "2");
            recording = true;
        }

        if( (temp >= 0 && temp <= 2100) && recording == true )
        {

            Log.i("TAG", "final run");
            //isRecording = false;

            txv.setText("Stop Record.");
            //*/
            tempIndex++;
            audioRecorder.stop();
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
    }
}

本函数的作用: 如果你调用这个函数,录音机就会开始录音,一旦你发出声音(如果有噪音通知它也会停止。)它会停止录音并保存到文件(pcm格式)。