目录
一、播放音频
MediaPlayer的工作流程
具体代码实现
二、播放视频
具体代码实现
学完本篇文章可以收获如何播放音频和视频。
一、播放音频
播放音频需要使用MediaPlayer类实现,它对各种格式的音频文件提供了全面的控制方法,下面是MediaPlayer类较为常用的控制方法。
MediaPlayer的工作流程
首先创建一个MediaPlayer对象,然后调用setDataSource()方法来设置音频文件的路径,再调用prepare()方法使MediaPlayer进入到准备状态,然后调用start()方法就可以开始播放音频,调用pause()方法就会暂停播放,调用reset()方法就会停止播放。
具体代码实现
新建一个PlayAudioTest项目。
修改activity_main.xml文件,代码如下:
三个按钮分别执行播放、暂停和停止操作。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent" ><Buttonandroid:id="@+id/play"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Play" /><Buttonandroid:id="@+id/pause"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Pause" /><Buttonandroid:id="@+id/stop"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Stop" /></LinearLayout>
然后修改MainActivity代码,如下:
首先创建一个MediaPlayer实例,然后在onCreate()方法里进行运行时权限处理,动态申请WRITE_EXTERNAL_STORAGE权限,这是因为我们将在SD卡中设置一个音频文件,为了播放这个文件必须访问SD卡的权限。
用户同意授权后调用initMediaPlayer()方法为MediaPlayer对象进行初始化操作,在initMediaPlayer()方法中,先通过创建一个File对象来指定音频文件路径,需要提前在SD卡的根目录下放置一个名为music.mp3的音频文件。
最后在onDestroy()方法中,分别调用stop()方法和release()方法,将与MediaPlayer相关的资源释放掉。
public class MainActivity extends AppCompatActivity implements View.OnClickListener{private MediaPlayer mediaPlayer = new MediaPlayer();@Overrideprotected 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(this);pause.setOnClickListener(this);stop.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}}private void initMediaPlayer() {try {File file = new File(Environment.getExternalStorageDirectory(), "music.mp3");mediaPlayer.setDataSource(file.getPath()); // 指定音频文件的路径mediaPlayer.prepare(); // 让MediaPlayer进入到准备状态} catch (Exception e) {e.printStackTrace();}}@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);switch (requestCode) {case 1:if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {initMediaPlayer();} else {Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();finish();}break;default:}}@Overridepublic 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(); // 停止播放initMediaPlayer();}break;default:break;}}@Overrideprotected void onDestroy() {super.onDestroy();if (mediaPlayer != null) {mediaPlayer.stop();mediaPlayer.release();}}}
最后在AndroidManifest.xml中声明权限,daima 如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />.............
二、播放视频
播放视频使用VideoView类实现,主要有以下使用方法:
具体代码实现
新建PlayVideoTest项目。
修改activity_main.xml代码如下:
三个按钮分别用于播放、暂停和重新播放。VideoView用于显示视频。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><Buttonandroid:id="@+id/play"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="Play" /><Buttonandroid:id="@+id/pause"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="Pause" /><Buttonandroid:id="@+id/replay"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="Replay" /></LinearLayout><VideoViewandroid:id="@+id/video_view"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>
修改MainActivity代码,如下:
和前面的播放音频代码类似,注意需要先在SD卡的根目录下放置一个名为movie.mp4的视频文件。
public class MainActivity extends AppCompatActivity implements View.OnClickListener{private VideoView videoView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);videoView = (VideoView) findViewById(R.id.video_view);Button play = (Button) findViewById(R.id.play);Button pause = (Button) findViewById(R.id.pause);Button replay = (Button) findViewById(R.id.replay);play.setOnClickListener(this);pause.setOnClickListener(this);replay.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 {initVideoPath(); // 初始化MediaPlayer}}private void initVideoPath() {File file = new File(Environment.getExternalStorageDirectory(), "movie.mp4");videoView.setVideoPath(file.getPath()); // 指定视频文件的路径}@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);switch (requestCode) {case 1:if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {initVideoPath();} else {Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();finish();}break;default:}}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.play:if (!videoView.isPlaying()) {videoView.start(); // 开始播放}break;case R.id.pause:if (videoView.isPlaying()) {videoView.pause(); // 暂停播放}break;case R.id.replay:if (videoView.isPlaying()) {videoView.resume(); // 重新播放}break;}}@Overrideprotected void onDestroy() {super.onDestroy();if (videoView != null) {videoView.suspend();}}}
效果如下: