📜  Kotlin Android Media Player

📅  最后修改于: 2021-01-05 08:36:53             🧑  作者: Mango

Kotlin Android Media Player

MediaPlayer是用于控制音频/视频文件和流的播放的类。

android.media.MediaPlayer类用于控制音频或视频文件。它访问内置的媒体播放器服务,例如播放音频,视频等。要使用MediaPlayer类,我们必须通过调用该类的create()方法来调用其创建实例。

MediaPlayer类的方法

MediaPlayer类有几种可用的方法。其中一些如下:

Method Description
public void setDataSource(String path) It sets the data source (file path or http url) to use.
public void prepare() It prepares the player for playback synchronously.
public void start() It starts or resumes the playback.
public void stop() It stops the playback.
public void pause() It pauses the playback.
public boolean isPlaying() It checks if the media player is playing.
public void seekTo(int millis) It seeks to specified time in milliseconds.
public void setLooping(boolean looping) It sets the player for looping or non-looping.
public boolean isLooping() It checks if the player is looping or non-looping.
public void selectTrack(int index) It selects a track for the specified index.
public int getCurrentPosition() It returns the current playback position.
public int getDuration() It returns duration of the file.
public void setVolume(float leftVolume,float rightVolume) It sets the volume on this player.

带有SeekBar的Android MediaPlayer示例

在此示例中,我们将创建具有播放控制功能(如播放,暂停和停止)的Media Player。我们还集成了SeekBar以显示媒体播放器的进度。

activity_main.xml

在activity_main.xml布局文件中,我们添加了用于控制媒体播放的按钮,用于显示歌曲持续时间的TextView和用于显示媒体文件进度的SeekBar。




    

MianActivity.kt

MediaPlayer类的实例是使用MediaPlayer.create()方法创建的。在此示例中,我们从原始目录读取媒体文件。 MediaPlayer.start()方法开始播放媒体文件, MediaPlayer.pause()方法暂停媒体,而Media.stop()方法停止播放媒体文件。

package example.javatpoint.com.kotlinmediaplayer

import android.media.MediaPlayer
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import android.os.Handler
import android.widget.SeekBar

class MainActivity : AppCompatActivity() {

    private lateinit var mediaPlayer: MediaPlayer
    private lateinit var runnable:Runnable
    private var handler: Handler = Handler()
    private var pause:Boolean = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Start the media player
        playBtn.setOnClickListener{
            if(pause){
                mediaPlayer.seekTo(mediaPlayer.currentPosition)
                mediaPlayer.start()
                pause = false
                Toast.makeText(this,"media playing",Toast.LENGTH_SHORT).show()
            }else{

                mediaPlayer = MediaPlayer.create(applicationContext,R.raw.school_bell)
                mediaPlayer.start()
                Toast.makeText(this,"media playing",Toast.LENGTH_SHORT).show()

            }
            initializeSeekBar()
            playBtn.isEnabled = false
            pauseBtn.isEnabled = true
            stopBtn.isEnabled = true

            mediaPlayer.setOnCompletionListener {
                playBtn.isEnabled = true
                pauseBtn.isEnabled = false
                stopBtn.isEnabled = false
                Toast.makeText(this,"end",Toast.LENGTH_SHORT).show()
            }
        }
        // Pause the media player
        pauseBtn.setOnClickListener {
            if(mediaPlayer.isPlaying){
                mediaPlayer.pause()
                pause = true
                playBtn.isEnabled = true
                pauseBtn.isEnabled = false
                stopBtn.isEnabled = true
                Toast.makeText(this,"media pause",Toast.LENGTH_SHORT).show()
            }
        }
        // Stop the media player
        stopBtn.setOnClickListener{
            if(mediaPlayer.isPlaying || pause.equals(true)){
                pause = false
                seek_bar.setProgress(0)
                mediaPlayer.stop()
                mediaPlayer.reset()
                mediaPlayer.release()
                handler.removeCallbacks(runnable)

                playBtn.isEnabled = true
                pauseBtn.isEnabled = false
                stopBtn.isEnabled = false
                tv_pass.text = ""
                tv_due.text = ""
                Toast.makeText(this,"media stop",Toast.LENGTH_SHORT).show()
            }
        }
        // Seek bar change listener
        seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                if (b) {
                    mediaPlayer.seekTo(i * 1000)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
            }
        })
    }
    // Method to initialize seek bar and audio stats
    private fun initializeSeekBar() {
        seek_bar.max = mediaPlayer.seconds

        runnable = Runnable {
            seek_bar.progress = mediaPlayer.currentSeconds

            tv_pass.text = "${mediaPlayer.currentSeconds} sec"
            val diff = mediaPlayer.seconds - mediaPlayer.currentSeconds
            tv_due.text = "$diff sec"

            handler.postDelayed(runnable, 1000)
        }
        handler.postDelayed(runnable, 1000)
    }
}
// Creating an extension property to get the media player time duration in seconds
val MediaPlayer.seconds:Int
    get() {
        return this.duration / 1000
    }
// Creating an extension property to get media player current position in seconds
val MediaPlayer.currentSeconds:Int
    get() {
        return this.currentPosition/1000
    }

输出: