gpt4 book ai didi

java - MediaPlayer - setAudioAttributes 无法正常工作

转载 作者:行者123 更新时间:2023-12-01 16:44:05 25 4
gpt4 key购买 nike

我正在尝试创建一个警报,一切正常,但流类型始终是媒体,即使我使用 STREAM_ALARM,因为 setStreamType 已弃用,我'我使用 setAudioAttributes 代替,但它似乎不起作用。这是我的代码:

class AlarmRingtoneManager(val context: Context) {

private lateinit var mediaPlayer: MediaPlayer

fun start() {
mediaPlayer = MediaPlayer.create(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.apply {
setAudioAttributes(AudioAttributes.Builder()
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
.setLegacyStreamType(AudioManager.STREAM_ALARM)
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build())
isLooping = true
start()
}
}

fun stop() {
mediaPlayer.stop()
}
}

最佳答案

问题是您正在使用方法 MediaPlayer.create() 创建 MediaPlayer,并且无法更改 AudioAttributes > 稍后如果你这样做的话。

来自the documentation :

Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.

When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.

Note that since prepare() is called automatically in this method, you cannot change the audio session ID (see setAudioSessionId(int)) or audio attributes (see setAudioAttributes(android.media.AudioAttributes) of the new MediaPlayer.

无需使用 create(),只需使用默认构造函数 new MediaPlayer(); 实例化 MediaPlayer 即可。然后,使用 setDataSource() 方法设置源,并像之前一样设置其余的 AudioAttributes。

我不了解 Kotlin,但在 Java 中它看起来像这样:

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(AudioAttributes.Builder()
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
.setLegacyStreamType(AudioManager.STREAM_ALARM)
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
mediaPlayer.setDataSource(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();

关于java - MediaPlayer - setAudioAttributes 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56210872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com