将初始音量设置为电话铃声音量

时间:2012-05-23 02:13:58

标签: android

我试图在用户打开应用程序时将其设置为将音乐的音量设置为他们拥有手机铃声音量的任何内容。这是我的代码到目前为止,但我不完全确定setVolume(float,float)上的参数是什么。 android文档并不能很好地解释它。我的代码在这里做错了什么?

  AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

   mPlayer = MediaPlayer.create(this, R.raw.song);
   mPlayer.setOnErrorListener(this);

   if(mPlayer!= null)
    {         
    mPlayer.setLooping(true);
    mPlayer.setVolume(currentVolume,1);
}

1 个答案:

答案 0 :(得分:4)

看起来audio.setStreamVolume是您想要的,但是传入STREAM_MUSIC而不是STREAM_RING。

注意:音乐音量和铃声音量可能会有不同的最大值,因此您需要将它们标准化。使用getStreamMaxVolume。

我之前没有这样做过,我没有编译过这个,但代码看起来应该是这样的

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

// Get the current ringer volume as a percentage of the max ringer volume.
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);
int maxRingerVolume = audio.getStreamMaxVolume(AudioManager.STREAM_RING);
double proportion = currentVolume/(double)maxRingerVolume;

// Calculate a desired music volume as that same percentage of the max music volume.
int maxMusicVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int desiredMusicVolume = (int)(proportion * maxMusicVolume);

// Set the music stream volume.
audio.setStreamVolume(AudioManager.STREAM_MUSIC, desiredMusicVolume, 0 /*flags*/);
相关问题