如何在 android 4.0 中以编程方式打开/关闭扬声器 [英] how to turn speaker on/off programmatically in android 4.0

查看:35
本文介绍了如何在 android 4.0 中以编程方式打开/关闭扬声器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过媒体播放器播放文件,我想提供诸如开/关扬声器、通过耳机播放、蓝牙等选项.我尝试了以下适用于 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 to programmatically 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:我已在清单中授予此权限:

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

android.permission.MODIFY_AUDIO_SETTINGS 

推荐答案

这样的事情可能适用于某些设备(我只在 XPeria P 上测试过):

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

final static int FOR_MEDIA = 1;
final static int FORCE_NONE = 0;
final static int FORCE_SPEAKER = 1;

Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
// To get back to the default behaviour, use the combination FOR_MEDIA,FORCE_NONE.

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.

这篇关于如何在 android 4.0 中以编程方式打开/关闭扬声器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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