在Android Studio中通过录音机检测语音 [英] Detect voice by audio recorder in android studio

查看:134
本文介绍了在Android Studio中通过录音机检测语音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

Android应用程序中的语音检测

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

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.

请帮助我〜

推荐答案

好,我解决了我的问题,这是我的解决方案.我修改了来自以下网址的代码: Android应用程序中的语音检测

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;
        }
    }
}

此功能的功能:如果调用此功能,录音机将开始录音,并在发出声音后(通知是否有噪音也将停止.)它将停止录音并保存到文件(pcm格式).

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).

这篇关于在Android Studio中通过录音机检测语音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆