将音量设置为特定值并再次设置

发布于 2024-12-02 02:22:12 字数 738 浏览 2 评论 0原文

我希望我的用户能够选择以尽可能高的音量播放警报声。

为此,我需要将媒体音量设置为最大,播放闹钟并将音量设置回原始状态。

为了进行测试,我有一个带有此 onClick 事件的按钮:

public void playAlarm(View view) {
  AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
  audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

  MediaPlayer mediaPlayer = MediaPlayer.create(view.getContext(), R.raw.alarm);
  mediaPlayer.start();

  audio.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND);
}

警报声音以原始音量播放,而不是以最大音量播放。

我做错了什么?

I would like my users to be able to choose that an alarm-sound plays at the highest possible volume.

For this I need to set media volume to max, play the alarm and set the volume back to the original state.

For testing I have a button with this onClick-event:

public void playAlarm(View view) {
  AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
  audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

  MediaPlayer mediaPlayer = MediaPlayer.create(view.getContext(), R.raw.alarm);
  mediaPlayer.start();

  audio.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND);
}

The alarm-sound is playing at the original volume, and not at max volume.

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥醉 2024-12-09 02:22:12
mediaPlayer.start()

实际上并不播放声音。它安排它尽快播放并立即返回。因此,当声音播放时,音量就恢复正常了。声音播放完毕后,您需要使用 http 设置音量://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener.html

mediaPlayer.start()

does not actually play the sound. It schedules it for playing asap and returns immediately. Therefore, by the time the sound is played, the volume is back to normal. You need to set the volume back once the sound is done playing, using an http://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文