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

查看:185
本文介绍了如何在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天全站免登陆