Play multimedia files on Android

Play multimedia files

Play audio

Playing audio files in Android is generally implemented using the MediaPlay class, which provides a very comprehensive control method for audio files in multiple formats, which makes the work of playing music very simple.
The following is a list of some of the more commonly used control methods in the MediaPlayer class

setDataSource() sets the location of the audio file to be played

prepare() call this method to complete the preparation work before starting to play

start() start or continue playing audio

pause() Pause playing audio

reset() resets the MediaPlayer object to the state just created

seekTo() starts playing audio from the specified position

stop() Stop playing audio. The MediaPlayer object after calling this method can no longer play audio

release() releases resources related to the MediaPlayer object

isPlayer() determines whether the current MediaPlayer is playing audio

getDuration() gets the duration of the loaded audio file.

After a brief understanding of the above methods, we will sort out the workflow of MediaPlayer.

First, you need to create a MediaPlayer object, then call the setDataSource() method to set the path of the audio file, then call the prepare() method to make the MediaPlayer enter the ready state, and then call the **start() method to start playing the audio, call pause () method will pause playback, and call reset()** method will stop playback.

Let us learn through a specific example, create a new PlayAudioTest project, and then modify the code in activity_main:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertival">

    <Button
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play"
        />
    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pause"
        />
    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop"
        />


</LinearLayout>

Three buttons are placed in the layout, which are used to play, pause and stop the audio file.
Then modify the code in MainActivity:

package net.nyist.lenovo.playaudiotest;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
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 java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{


    private MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button play = (Button) findViewById(R.id.play);
        Button pause = (Button) findViewById(R.id.pause);
        Button stop = (Button) findViewById(R.id.stop);
        play.setOnClickListener((View.OnClickListener) this);
        pause.setOnClickListener((View.OnClickListener) this);
        stop.setOnClickListener((View.OnClickListener) this);
        //由于待会要在SD卡中放置一个音频文件,程序为了播放这个音频文件必须拥有访问SD卡的权限才行.
        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
        }

    }
    private void initMediaPlayer(){
        try {
            File file = new File(Environment.getExternalStorageDirectory(),"music.mp3");
            mediaPlayer.setDataSource(file.getPath());//指定音频文件的路径
            mediaPlayer.prepare();//让MediaPlayer进入到准备状态
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    initMediaPlayer();
                }else {
                    Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();
                    finish();
                    //注意如果用户拒绝了权限申请,那么就调用finish()方法将程序直接关掉
                    //因为如果没有SD卡的访问权限,我们这个程序什么都干不了。
                }
                break;
            default:
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.play:
                if (!mediaPlayer.isPlaying()){
                    mediaPlayer.start();//开始播放
                }
                break;
            case R.id.pause:
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.pause();//暂停播放
                }
                break;
            case R.id.stop:
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.reset();//停止播放
                }
                break;
            default:
                break;

        }
    }

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

In addition, do not forget to declare the permissions used in the AndroidManifest.xml file, as shown below:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	    package="net.nyist.lenovo.playaudiotest">
	    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
	。。。。。。
	</manifest>

Guess you like

Origin blog.csdn.net/i_nclude/article/details/77749541