Android MediaPlayer倍速播放功能

Android MediaPlayer在API 23即6.0以上支持了设置播放速率。
下面将介绍怎么使用这个功能。

  1. 接口
MediaPlayer.setPlaybackParams(PlaybackParams params) throws IllegalStateException, IllegalArgumentException

接口说明:
(1) 使用这个接口可以进行播放速率的设置。
(2) 播放器prepared状态之前调用这个方法不会更改播放器的状态。
(3) prepared状态之后设置速率0等同于调用pause(),当调用start恢复播放以后,将以原来的速率进行播放。
(4) prepared状态之后设置非0的速率等同于调用start()。
(5) 当播放器还未初始化或者已经被释放的时候设置会抛IllegalStateException的异常。
(6) 当参数不支持的时候会抛IllegalArgumentException的异常。

  1. 设置时机要求:
    合法的时机:Initialized, Prepared, Started, Paused, PlaybackCompleted, Error
    非法的时机:Idle, Stopped
  1. 示例


    image

布局文件:

Activity的代码如下:

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

    player = MediaPlayer.create(this, R.raw.sample);

    setPlayPauseButton();
    setSpeedOptions();

}
private void setPlayPauseButton() {
    final Button playPauseButton = (Button) findViewById(R.id.buttonPlayPause);
    playPauseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (player.isPlaying()) {
                player.pause();
            } else {
                player.start();
            }
        }
    });
}

播放速率控制相关代码:

// this is the main player 
private MediaPlayer player;

// speed values displayed in the spinner
private String[] getSpeedStrings() {
    return new String[]{"1.0", "1.2", "1.4", "1.6", "1.8", "2.0"};
}

private void setSpeedOptions() {
    final Spinner speedOptions = (Spinner)findViewById(R.id.speedOptions);
    String[] speeds = getSpeedStrings();

    ArrayAdapter arrayAdapter =  new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_dropdown_item, speeds);
    speedOptions.setAdapter(arrayAdapter);

    // change player playback speed if a speed is selected
    speedOptions.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
            if (player != null) {
                float selectedSpeed = Float.parseFloat(
                    speedOptions.getItemAtPosition(i).toString());

                changeplayerSpeed(selectedSpeed);
            }
        }

        @Override
        public void onNothingSelected(AdapterView adapterView) {

        }
    });
}

private void changeplayerSpeed(float speed) {
    // this checks on API 23 and up
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (player.isPlaying()) {
            player.setPlaybackParams(player.getPlaybackParams().setSpeed(speed));
        } else {
            player.setPlaybackParams(player.getPlaybackParams().setSpeed(speed));
            player.pause();
        }
    }
}

4.推荐阅读
腾讯视频多倍速播放产品设计

你可能感兴趣的:(Android MediaPlayer倍速播放功能)