Android 學習之《第一行代碼》第二版 筆記(二十)播放多媒體文件

通過點擊按鈕實現播放、暫停和關閉(重置)音頻和視頻

一、知識點

1. 音頻

在Android中一般使用MediaPlayer類來實現播放音頻文件。

方法名 功能描述
setDataSource() 設置要播放的音頻文件的位置
prepare() 在開始播放之前調用這個方法完成準備工作
start() 開始或繼續播放音頻
pause() 暫停播放音頻
reset() 將MediaPlayer對象重置到剛剛創建的狀態
seekTo() 從指定位置開始播放音頻
stop() 停止播放音頻。調用這個方法後的MediaPlayer對象無法再播放音頻
release() 釋放掉與MediaPlayer對象相關的資源
isPlaying() 判斷當前MediaPlayer是否正在播放音頻
getDuration() 獲取載入的音頻文件的時長

2. 視頻

主要使用VideoView類來實現,這個類將視頻的顯示和控制集於一身。這個類只是幫我們做了一個很好的封裝,它的背後仍然是使用MediaPlayer來對視頻文件進行控制的。

方法名 功能描述
setVideoPath() 設置要播放的視頻文件的位置
start() 開始或繼續播放視頻
pause() 暫停播放視頻
resume() 將視頻重頭開始播放
seekTo() 從指定位置開始播放視頻
isPlaying() 判斷當前是否正在播放視頻
getDuration() 獲取載入的視頻文件的時長

二、Demo

1. 效果圖

播放多媒體文件1
播放多媒體文件2

2. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.thinkpad.mediaplayer.MainActivity">

    <Button
        android:id="@+id/play_music"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="播放音樂"/>
    <Button
        android:id="@+id/pause_music"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="暫停音樂"/>
    <Button
        android:id="@+id/stop_music"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="關閉音樂"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000000"/>

    <Button
        android:id="@+id/play_video"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="播放視頻"/>
    <Button
        android:id="@+id/pause_video"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="暫停視頻"/>
    <Button
        android:id="@+id/replay_video"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="重置視頻"/>
    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

3. MainActivity.java

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private MediaPlayer mediaPlayer = new MediaPlayer(); //創建MediaPlayer對象

    //各個控件
    private Button playMusic;
    private Button pauseMusic;
    private Button stopMusic;
    private Button playVideo;
    private Button pauseVideo;
    private Button replayVideo;
    private VideoView videoView;

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

        //實例化控件對象
        playMusic = (Button)findViewById(R.id.play_music);
        pauseMusic = (Button)findViewById(R.id.pause_music);
        stopMusic = (Button)findViewById(R.id.stop_music);
        playVideo = (Button)findViewById(R.id.play_video);
        pauseVideo = (Button)findViewById(R.id.pause_video);
        replayVideo = (Button)findViewById(R.id.replay_video);
        videoView = (VideoView)findViewById(R.id.video_view);

        //設置點擊對象
        playMusic.setOnClickListener(this);
        pauseMusic.setOnClickListener(this);
        stopMusic.setOnClickListener(this);
        playVideo.setOnClickListener(this);
        pauseVideo.setOnClickListener(this);
        replayVideo.setOnClickListener(this);

        //運行時權限檢查
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            },1);
        }else{
            initMediaPlayer();//初始化MediaPlayer
            initVideoPath();//初始化Viedo
        }
    }

    //初始化MediaPlayer
    private void initMediaPlayer(){
        try{
            File file = new File(Environment.getExternalStorageDirectory(),"xsdhls.mp3");
            mediaPlayer.setDataSource(file.getPath()); //指定音頻文件的路徑
            mediaPlayer.prepare();//讓MediaPlayer進入到準備狀態
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //初始化Video
    private void initVideoPath(){
        File file = new File(Environment.getExternalStorageDirectory(),"如約而至許嵩.mp4");
        videoView.setVideoPath(file.getPath());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initMediaPlayer();
                    initVideoPath();
                } else {
                    Toast.makeText(this, "你選的嘛偶像!", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.play_music:
                if (!mediaPlayer.isPlaying()){
                    mediaPlayer.start();//開始播放音樂
                }
                break;
            case R.id.pause_music:
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.pause();//暫停音樂
                }
                break;
            case R.id.stop_music:
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.reset(); //停止音樂
                    initMediaPlayer();
                }
                break;
            case R.id.play_video:
                if (!videoView.isPlaying()){
                    videoView.start();//開始播放視頻
                }
                break;
            case R.id.pause_video:
                if (videoView.isPlaying()){
                    videoView.pause();//暫停播放視頻
                }
                break;
            case R.id.replay_video:
                if (videoView.isPlaying()){
                    videoView.resume();//重新播放視頻
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if (videoView != null){
            videoView.suspend();
        }
    }
}

4. AndroidManifest.xml

添加權限說明

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

整理學習自郭霖大佬的《第一行代碼》
目前小白一名,持續學習Android中,如有錯誤請批評指正!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章