[已解決] MediaPlayer.setVolume設定聲音大小失效問題
阿新 • • 發佈:2018-12-31
寫一個很平常的音樂播放方法,發現聲音很小,於是呼叫MediaPlayer.setVolume來設定聲音,結果無效,程式碼如下:
private static MediaPlayer m = null;
public void play(Context context) {
m = new MediaPlayer();
m = MediaPlayer.create(context, R.raw.myMusic);
m.setAudioStreamType(AudioManager.STREAM_MUSIC);
m.setVolume(1 f, 1f);
m.start();
m.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer arg0) {
m.release();
Log.d("MediaPlayer:", "release");
}
});
查詢到的解決方法是將setVolume方法放到play之後,如下:
m = new MediaPlayer();
m = MediaPlayer.create(context, R.raw.myMusic);
m.setAudioStreamType(AudioManager.STREAM_MUSIC);
m.start();
m.setVolume(1f, 1f);
再次測試發現聲音已經變大,問題解決
檢視setVolume原始碼的註釋:
public void setVolume(float leftVolume, float rightVolume)
/**
* Sets the volume on this player.
* This API is recommended for balancing the output of audio streams
* within an application. Unless you are writing an application to
* control user settings, this API should be used in preference to
* {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
* a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
* UI controls should be scaled logarithmically.
*
* @param leftVolume left volume scalar
* @param rightVolume right volume scalar
*/
其中的兩個引數分別是左右聲道聲音大小,取值範圍為0~1