Speed Control of MediaPlayer in Android

前端 未结 6 1341
别那么骄傲
别那么骄傲 2020-11-28 09:41

I am developing a player app and I am using MediaPlayer for that.

Now, I want to change the speed of the playing track.

I\'ve seen so many apps with this fu

相关标签:
6条回答
  • 2020-11-28 09:42

    soundpool only supports relatively small sound effect files that can be preloaded. You will get heap overflows with any useful length music track.

    0 讨论(0)
  • 2020-11-28 09:43
    PlaybackParams playbackParams = new PlaybackParams();
    playbackParams.setSpeed(2);
    playbackParams.setPitch(1);
    playbackParams.setAudioFallbackMode(
        PlaybackParams.AUDIO_FALLBACK_MODE_DEFAULT);
    mMediaPlayer.setPlaybackParams(playbackParams);
    
    0 讨论(0)
  • 2020-11-28 09:49

    The MediaPlayer does not provide this feature but SoundPool has this functionality. The SoundPool class has a method called setRate (int streamID, float rate). If you are interested in the API have a look here.

    This Snippet will work.

     float playbackSpeed=1.5f; 
     SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    
     soundId = soundPool.load(Environment.getExternalStorageDirectory()
                             + "/sample.3gp", 1);
     AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
     final float volume = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    
     soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()
     {
         @Override
         public void onLoadComplete(SoundPool arg0, int arg1, int arg2)
         {
             soundPool.play(soundId, volume, volume, 1, 0, playbackSpeed);
         }
     });
    
    0 讨论(0)
  • 2020-11-28 09:52

    Now you could use

    mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed)

    for API 23 and up!

    0 讨论(0)
  • 2020-11-28 10:00

    Beginning API 23, MediaPlayer can set playback speed using this method.

    Class MediaPlayer

    public void setPlaybackParams (PlaybackParams params) Added in API level 23

    Sets playback rate using PlaybackParams. Parameters params PlaybackParams: the playback params. Throws IllegalStateException if the internal player engine has not been initialized. IllegalArgumentException if params is not supported.

    Sample code:

    MediaPlayer mp = ...; //Whatever
    float speed = 0.75f;     
    mp.setPlaybackParams(mp.getPlaybackParams().setSpeed(speed));
    

    For API < 23, refer to Vipul Shah's answer above (or below).

    0 讨论(0)
  • 2020-11-28 10:02

    The MediaPlayer class doesn't give this functionality. Instead use the SoundPool class. It has a method called setRate (int streamID, float rate). Read this for further info. Here is a sample code for you to work with it.

    0 讨论(0)
提交回复
热议问题