且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android:如何以最大音量播放音乐?

更新时间:2023-02-27 07:39:18

我建议使用 getStreamMaxVolume 和 setStreamVolume 来做到这一点:

I'd suggest using getStreamMaxVolume and setStreamVolume to do this:

int origionalVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);

完成后,只需将其设置回原始音量即可.

Then once you're done just set it back to the original volume.

我想我被打败了,嗯嗯:)

I think I was beaten to the punch, ahh well :)

一些实际执行此操作的代码,我使用的是 MediaPlayer 而不是声音池,因为这为您提供了播放完整回调,而声音池中似乎不存在:

Some code that actually does this, I'm using the MediaPlayer rather than the soundpool as this gives you a play complete callback which doesn't appear to be present on the soundpool:

final AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
final int originalVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource("content://media/internal/audio/media/97");
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener()
{
   @Override
   public void onCompletion(MediaPlayer mp)
   {
      mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0);
   }
});

顺便说一下 with call mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 0, 0, 1.0f); streamVolume 值实际上是浮点数 0 -> 1,代表一个最大值的百分比,所以你真的只想在那里输入 1.0f.

Btw the with call mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 0, 0, 1.0f); the streamVolume values are actually floats 0 -> 1 that represent a percentage of the maximum value so you'd really just want to put in 1.0f there.