简体   繁体   中英

How to mute earpiece using AudioManager?

Can anybody tell me how to mute earpiece in android (targetSdkVersion 26). I tried this:

audioManager.setSpeakerphoneOn(false);

but it only mutes the speaker, not the earpiece.
I also tried this:

audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setStreamVolume(STREAM_VOICE_CALL, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

and this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    am.requestAudioFocus(new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE)
              .setAudioAttributes(new AudioAttributes.Builder().setUsage(USAGE_VOICE_COMMUNICATION).build()).build());
    am.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}

with the same effect.

I work with webrtc and my goal is to mute/unmute the output audio. Thank you very much.

Here is how to mute/unmute:

private RTCSession currentSession;

private void setAudioEnabled(boolean isAudioEnabled) {
    if (currentSession != null && currentSession.getMediaStreamManager() != null) {
        currentSession.getMediaStreamManager().getLocalAudioTrack().setEnabled(isAudioEnabled);
    }
}

And also if you want to switch between different audio sources:

public void onSwitchAudio() {
    if (audioManager.getSelectedAudioDevice() != AppRTCAudioManager.AudioDevice.SPEAKER_PHONE) {
        audioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
    } else {
        if (audioManager.getAudioDevices().contains(AppRTCAudioManager.AudioDevice.BLUETOOTH)) {
            audioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.BLUETOOTH);
        } else if (audioManager.getAudioDevices().contains(AppRTCAudioManager.AudioDevice.WIRED_HEADSET)) {
            audioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.WIRED_HEADSET);
        } else {
            audioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM