【发布时间】:2015-04-10 06:54:32
【问题描述】:
我在我的应用中构建了一个简单的视频播放器。
我只想通过耳机而不是扬声器播放音频。
所以,我做了以下
onCreate
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
....
@SuppressWarnings("deprecation")
private void checkJack() {
if(Constants.HEADSET_ONLY && !musicReceiverStarted) {
Log.v(TAG + " | AudioManager checkJack", "Running checkJack()");
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
try
{
if(!audio.isWiredHeadsetOn()) {
Log.v(TAG + " | AudioManager checkJack", "Headset is unplugged");
audio.setStreamMute(AudioManager.STREAM_MUSIC, true); // Mute
Toast.makeText(DuplicatedPlayerActivity.this, "Please plug in your headset to enjoy the sound.", Toast.LENGTH_SHORT).show();
}
else {
Log.v(TAG + " | AudioManager checkJack", "Headset is plugged");
audio.setStreamMute(AudioManager.STREAM_MUSIC, false); // UnMute
}
}
catch (Exception e) { e.printStackTrace(); }
}
}//end checkJack
然后我有一个接收器:
private class MusicIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
musicReceiverStarted = true;
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d(TAG + " | AudioManager", "Headset is unplugged");
audio.setStreamMute(AudioManager.STREAM_MUSIC, true); // Mute
Toast.makeText(DuplicatedPlayerActivity.this, "Please plug in your headset to enjoy the sound.", Toast.LENGTH_SHORT).show();
break;
case 1:
Log.d(TAG + " | AudioManager", "Headset is plugged");
audio.setStreamMute(AudioManager.STREAM_MUSIC, false); // UnMute
break;
default:
Log.d(TAG + " | AudioManager", "I have no idea what the headset state is");
audio.setStreamMute(AudioManager.STREAM_MUSIC, true); // Mute
Toast.makeText(DuplicatedPlayerActivity.this, "Please plug in your headset to enjoy the sound.", Toast.LENGTH_SHORT).show();
}
}//end if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG))
}//end onReceive
}//end MusicIntentReceiver
现在的问题是:两个函数都运行正确。但是在 checkJack() 中的音频已被静音之后;它不会在 MusicIntentReceiver() 中取消静音;
此外,MusicIntentReceiver() 仅在插孔状态发生更改时才会执行。所以我不能第一次用它来静音,因为它永远不会被执行。
任何建议。
【问题讨论】:
-
您确定您没有将流静音两次(或更多次)吗?您必须将流取消静音的次数与静音次数相同。
标签: java android android-resources android-audiomanager