如何正确设置 MediaPlayer 音频流类型 [英] How to correctly set MediaPlayer audio stream type

查看:34
本文介绍了如何正确设置 MediaPlayer 音频流类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一种方法来为每个不同的流(媒体、通知、铃声等)调整音量设置,并有一种方法来预览每个流的输出声级.我相信我有正确的实现,但是当我设置输出流类型时,没有播放声音.

I'm trying to create a way to adjust volume settings for each of the different streams (media, notification, ringtone, etc) and have a way to preview the output sound level of each stream. I believe I have the correct implementation, but when I set the output stream type, there is no sound that plays.

以下是正确播放用户选择的闹钟声音的代码:

Here is the code that correctly plays the user's selected alarm sound:

Uri mediaUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
MediaPlayer mp=MediaPlayer.create(getApplicationContext(), mediaUri);
//mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.start();`

注释掉的那行是导致我出现问题的原因.我想在不同音频流的音量级别听到警报声,但是当我为 STREAM_ALARM 或任何其他音频流包含该行时,根本没有声音播放.知道这里会发生什么吗?

That commented out line is what is causing me problems. I would like to hear the alarm sound at the volume levels of the different audio streams, but when I include that line for STREAM_ALARM or any other audio stream, no sound at all plays. Any ideas what could be going on here?

推荐答案

好的,我在进行了更多测试后找到了解决方案,它看起来像这样,以防其他人遇到我遇到的同样问题.清单中需要 MODIFY_AUDIO_SETTINGS 权限才能使其工作.

Okay, I found the solution after a bit more testing and it looks like this, in case anyone else runs into the same problem I was having. The MODIFY_AUDIO_SETTINGS permission is needed in the Manifest for this to work.

AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL);
MediaPlayer mp=new MediaPlayer();
Uri ringtoneUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
try
{
    mp.setDataSource(getApplicationContext(), ringtoneUri);
    mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
    mp.prepare();
    mp.start();
}
catch(Exception e)
{
    //exception caught in the end zone
}

这篇关于如何正确设置 MediaPlayer 音频流类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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