android-studiodetectvoiceaudiorecord

Detect voice by audio recorder in android studio


Well, I would like to implement a function, such when the application starts, the recorder will start to recording, and when the user keeps silence there is nothing going to happen until the user speaks. Then, it will save the PCM file of user's voice and then stop recording.

Voice Detection in Android Application

Above is the question I have found similar as mine, but the answer of this link can not work. And I don't know how to modify it, since I don't understand the concept of the code.

Please help me~


Solution

  • Well, I solved my problem, here is my solution. I modified the code came from this 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;
            }
        }
    }
    

    The function of this function: if you call this function, the recorder will start recording, and once you make sound(Notify if there are some noise it will stop too.) it will stop recording and save into file(pcm format).