简体   繁体   中英

setVolume Using MediaPlayer API is Not Working

I don't want to use AudioManager... Using the MediaPlayer API, my app is not able to set the volume to desired level. As it playes on previous level of volume which is set by Volume UP and Volume Down Key.

public class MainActivity extends AppCompatActivity {

    protected static MediaPlayer mp;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button next=(Button) findViewById(R.id.button);
        mp=MediaPlayer.create(this,R.raw.m1);
        mp.setVolume(0.02f,0.02f);
        mp.start();
        mp.setLooping(true);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Main2Activity.class);
                startActivity(intent);
            }
        });

As mentioned in documentation:

"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 setStreamVolume(int, int, int) which sets the volume of ALL streams of a particular type. "

https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float,%20float)

You can however set a stream to your mediaplayer and let is play on the desired stream like Music / Notification or Alarm which should suffice the req.

mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

Otherwise if you want to play some sound with certain level you have to use AudioManager API's to set a certain stream & set the volume of the stream and play the audio. This is a common practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM