2

ユーザーがアプリを開いたときに、音楽の音量を携帯電話の着信音の音量に設定するようにしようとしています。これはこれまでの私のコードですが、 setVolume(float, float) のパラメーターが何であるか正確にはわかりません。アンドロイドのドキュメントはそれをうまく説明していません。ここで私のコードが間違っているのは何ですか?

  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);
}
4

1 に答える 1

4

audio.setStreamVolumeが必要なように見えますが、STREAM_RINGの代わりにSTREAM_MUSICを渡します。

注:音楽の音量と呼び出し音の音量の最大値は異なる可能性があるため、正規化する必要があります。そのために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*/);
于 2012-05-23T02:22:48.557 に答える