Android MediaPlayer - 如何在 STREAM_ALARM 中播放? [英] Android MediaPlayer - how to play in the STREAM_ALARM?
问题描述
我已经尝试使用以下代码在我的应用程序中设置媒体播放器的音频流,但是当我这样做时,我在模拟器中听不到声音.如果我不为播放器设置流,则音频播放正常.我确定我用错了但不能锻炼如何,有什么帮助吗?
I've tried settings the audio stream of the media player in my application using the following code but when I do this I hear no sound in the emulator. If I don't set the stream for the player then the audio plays fine. I'm sure I'm using this wrong but cannot workout how, any help?
MediaPlayer player = MediaPlayer.create(getApplicationContext(), R.raw.test_audio);
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
player.setAudioStreamType(AudioManager.STREAM_ALARM);
player.start();
注意:我已经在清单中添加了 MODIFY_AUDIO_SETTINGS 权限.
Note: I've added the MODIFY_AUDIO_SETTINGS permission to my manifest already.
谢谢!
推荐答案
我不知道为什么会发生这种情况,但是下面的代码有效.您应该使用 setDataSource()
而不是 create()
设置数据源.
I don't know why this would happen, however the code below works. You should set the data source with setDataSource()
instead of with create()
.
此代码有效:
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setDataSource(this,Uri.parse("android.resource://PACKAGE_NAME/"+R.raw.soundfile));
mp.prepare();
mp.start();
此代码不起作用:
MediaPlayer mp = MediaPlayer.create(this, R.raw.soundfile);
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.prepare();
mp.start();
这篇关于Android MediaPlayer - 如何在 STREAM_ALARM 中播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!