问题描述
我做了很多谷歌搜索,但是其他人的解决方案对我来说却行不通.
I have done a lot of googling but other's solutions are not working for me.
我的目标是在报警通道上按需播放声音.
(因此,音量可以通过警报音量设置进行调整)
My goal is to play a sound on demand on the alarm channel.
(So the sound volume is adjusted by the alarm volume setting)
来自此线程我构建以下代码
mediaPlayerScan = MediaPlayer.create(getContext(), R.raw.scan_beep);
if (Build.VERSION.SDK_INT >= 21) {
mediaPlayerScan.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
} else {
mediaPlayerScan.setAudioStreamType(AudioManager.STREAM_ALARM);
}
它仍在音乐频道上播放.(IE音量是在音乐设置中调整的,不会发出警报)
It still plays on the music channel.(IE volume is adjusted in music setting not alarm)
我的直觉是我缺少权限之类的东西,但是我没有找到这样的权限.
My intuition is that i'm missing a permission or something, but I haven't found such a permission.
我正在Google Pixel 1上进行测试
I'm testing on a Google Pixel 1
谢谢,
内森
由于@ jeffery-blattman,以下代码对我有用
Thanks to @jeffery-blattman the following code works for me
mediaPlayerScan = new MediaPlayer();
try {
mediaPlayerScan.setDataSource(getContext(),
Uri.parse(getString(R.string.res_path) + R.raw.scan_beep));
if (Build.VERSION.SDK_INT >= 21) {
mediaPlayerScan.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
} else {
mediaPlayerScan.setAudioStreamType(AudioManager.STREAM_ALARM);
}
mediaPlayerScan.prepare();
} catch (IOException e) {
e.printStackTrace();
}
推荐答案
问题是create()
将MediaPlayer
置于不接受属性的状态(它将为您调用prepare()
).您需要使用更详细的机制来创建播放器.
The problem is that create()
puts the MediaPlayer
in a state where it won't accept the attributes (it calls prepare()
for you). You need to use the more verbose mechanism of creating the player.
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(...);
AudioAttributes attrs = new AudioAttributes.Builder().setUsage(usage).build();
mediaPlayer.setAudioAttributes(attrs);
new AsyncTask<Void,Void,Boolean>() {
@Override
protected Boolean doInBackground(Void... voids) {
try {
mediaPlayer.prepare();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean prepared) {
if (prepared) {
mediaPlayer.start();
}
}
}.execute();
这篇关于在Android的警报频道上播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!