如何打开扬声器/关闭编程的安卓4.0扬声器

2023-09-12 21:47:41 作者:长安归故里

我通过发挥媒体播放器的文件,我想给像扬声器选择开/关,播放不过耳机,蓝牙等。 我想下面的code效果很好,为Android 2.2,但我想要的东西,也可以工作2.2和4.0两种。 你能帮我怎么亲语法打开扬声器/关闭,并通过耳机播放?

I play a file through media player and I want to give options like speaker on/off, play though headset, bluetooth ,etc. I tried the below code which works well for android 2.2 but I want something that can also work for 2.2 and 4.0 both. Can you help me how to pro-grammatically turn the speaker on/off and playing via headphones ?

AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    if(isOn){
        audioManager.setMode(AudioManager.MODE_IN_CALL);    
        audioManager.setMode(AudioManager.MODE_NORMAL); 
    }else{
        //Seems that this back and forth somehow resets the audio channel
        audioManager.setMode(AudioManager.MODE_NORMAL);     
        audioManager.setMode(AudioManager.MODE_IN_CALL);        
    }
    audioManager.setSpeakerphoneOn(isOn);

P.S:我在清单授予该权限: android.permission.MODIFY_AUDIO_SETTINGS许可

P.S: I have given this permission in manifest: android.permission.MODIFY_AUDIO_SETTINGS permission

推荐答案

这样的事情可能工作在某些设备上(我只测试了上XPERIA P):

Something like this might work on some devices (I've only tested in on an XPeria P):

Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
// First 1 == FOR_MEDIA, second 1 == FORCE_SPEAKER. To go back to the default
// behavior, use FORCE_NONE (0).
setForceUse.invoke(null, 1, 1);

组合 FOR_MEDIA,FORCE_SPEAKER 通常仅用于内部路由FM收音机音频扬声器(因为FM收音机需要你有一个有线耳机/耳机插入到作为天线)。设备不具有FM无线电的功能(或者使用可替换的实施)可能会忽略的参数这种组合,因此这种方法不会这样的设备上工作。

The combination FOR_MEDIA, FORCE_SPEAKER is typically only used internally to route the FM-radio audio to the loudspeaker (since the FM-radio requires you to have a wired headset / headphone plugged in to act as an antenna). Devices that don't have FM-radio functionality (or uses an alternative implementation) might ignore this combination of parameters, so this method would not work on such a device.