在Android Studio中通过录音机检测语音

时间:2018-07-19 09:52:52

标签: android-studio detect voice audiorecord

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

Voice Detection in Android Application

以上是我发现的与我类似的问题,但此链接的答案无效。而且我不知道如何修改它,因为我不了解代码的概念。

请帮助我〜

1 个答案:

答案 0 :(得分:0)

好吧,我解决了我的问题,这是我的解决方案。 我修改了来自以下网址的代码: 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格式)。