[已解决] MediaPlayer.setVolume设置声音大小失效问题

写一个很平常的音乐播放方法,发现声音很小,于是调用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(1f, 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

你可能感兴趣的:(Android,android,mediaplayer)