How to detect if a microphone is present in android?

前端 未结 2 979
情书的邮戳
情书的邮戳 2021-01-12 05:30

I have a voice recognition part in my application to capture users voice input.

This is what I do

Intent voiceIntent = new Intent(RecognizerIntent.AC         


        
相关标签:
2条回答
  • 2021-01-12 05:52
    PackageManager pm = getPackageManager();
    boolean micPresent = pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
    

    Android API Reference: hasSystemFeature

    0 讨论(0)
  • 2021-01-12 06:01

    I added another answer but that is just a link that was broken after some time but here is the correct answer which includes the code.

    This is the code that you would need to use to start the voice recognizer intent. This checks if there are any intents available to handle the speech recognition intent.

    PackageManager pm = getPackageManager();
    List<?> activities = pm.queryIntentActivities(
                          new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    if (activities.size() > 0) {
        Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
        startActivityForResult(voiceIntent, REQUEST_CODE);
    
        Toast toast = Toast.makeText(this, "Loading Voice recognizer...", Toast.LENGTH_SHORT);
        toast.show();
    } else { 
        Toast.makeText(this, 
                       "This action is not available on this device.", 
                       Toast.LENGTH_SHORT).show();
    }
    

    On the top of that you ay also do another check to see if the microphone itself is present on the device.

    if (getPackageManager().hasSystemFeature( "android.hardware.microphone")) {
        //Microphone is present on the device
    }
    
    0 讨论(0)
提交回复
热议问题