文章目录
- MediaPlayer类
- 播放音频的实例
- VideoView类
- 播放视频的实例
MediaPlayer类
对多种格式的音频文件提供了全面的控制方法:
如何获得MediaPlayer实例?
- 通过构造函数:
MediaPlayer mp = new MediaPlayer();
- 调用 MediaPlayer.create() 方法:
MediaPlayer mp = MediaPlayer.create(this, R.raw.test);
由于 create
方法内会调用 setDataSource
和 prepare
,因此后续无需再进行这两个的步骤:
如何设置要播放的文件?
MediaPlayer 要播放的文件主要包括3个来源:
- 应用中的 resource 资源:
// 放在程序res/raw目录下名为的test文件
MediaPlayer.create(this, R.raw.test);
- 存储在SD卡或其他文件路径下的媒体文件
// 通过Environment.getExternalStorageDirectory()获得sd卡路径
// mediaPlayer.setDataSource(Environment.getExternalStorageDirectory(), "music.mp3");
mp.setDataSource("/sdcard/test.mp3");
// 然后需要将MediaPlayer置为prepare状态
mp.prepare();
- 网络上的媒体文件,流程同上,只是
setDataSource
参数为网上资源的Uri
。
重要的控制方法
- seekTo(): 定位方法,该方法是个异步方法,返回时并不意味着定位完成,尤其是播放的网络文件。真正定位完成时会触发
OnSeekComplete.onSeekComplete()
,如果需要可以调用setOnSeekCompleteListener(OnSeekCompleteListener)
设置监听器来处理的。 - prepareAsync() : 异步方式设置播放器进入
prepare
状态。
播放音频的实例
布局文件 audio_layout.xml
:
活动文件:
public class AudioActivity extends AppCompatActivity implements View.OnClickListener {private static final String TAG = "AudioActivity";private MediaPlayer mediaPlayer;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.audio_layout);Button button_play = findViewById(R.id.button_play);Button button_pause = findViewById(R.id.button_pause);Button button_stop = findViewById(R.id.button_stop);button_play.setOnClickListener(this);button_pause.setOnClickListener(this);button_stop.setOnClickListener(this);// 权限申请// 相等说明用户已授权,不等说明未授权if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){// 申请授权ActivityCompat.requestPermissions(this,new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);} else {initMediaPlayer(); // 初始化MediaPlayer}}private void initMediaPlayer() {mediaPlayer = MediaPlayer.create(this, R.raw.shan_gui);}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.button_play:if(!mediaPlayer.isPlaying()){mediaPlayer.start();Log.e(TAG, "点击play");}break;case R.id.button_pause:if(mediaPlayer.isPlaying()){mediaPlayer.pause();Log.e(TAG, "点击pause");}break;case R.id.button_stop:if(mediaPlayer.isPlaying()){mediaPlayer.reset();// reset方法中会调用close、clear方法将MediaPlayer的资源进行清除// 因此需要重新初始化MediaPlayerinitMediaPlayer();Log.e(TAG, "点击stop");}break;}}@Overridepublic 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_LONG).show();finish();}break;}}@Overrideprotected void onDestroy() {super.onDestroy();if(mediaPlayer != null){mediaPlayer.stop();mediaPlayer.release();mediaPlayer = null;}}
}
VideoView类
常用方法有:
播放视频的实例
布局文件 video_layout.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/button_vPlay"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="video play"/><Buttonandroid:id="@+id/button_vPause"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="video pause"/><Buttonandroid:id="@+id/button_vReplay"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="video replay"/></LinearLayout><VideoViewandroid:id="@+id/video_view"android:layout_width="match_parent"android:layout_height="wrap_content"/>
</LinearLayout>
- 三个按钮分别起到:播放、暂停、重置为视频开头的功能
VideoView
用以显示视频。
活动文件:
public class VideoActivity extends AppCompatActivity implements View.OnClickListener {private static final String TAG = "VideoActivity";private VideoView videoView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.video_layout);videoView = findViewById(R.id.video_view);Button button_vPlay = findViewById(R.id.button_vPlay);Button button_vPause = findViewById(R.id.button_vPause);Button button_vReplay = findViewById(R.id.button_vReplay);button_vPlay.setOnClickListener(this);button_vPause.setOnClickListener(this);button_vReplay.setOnClickListener(this);if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);}else {initVideoPath(); // 初始化VideoViewLog.e(TAG, "onCreate: initVideoPath over");}}private void initVideoPath() {Uri uri = Uri.parse("android.resource://"+getPackageName()+ "/"+R.raw.qinqin);videoView.setVideoURI(uri);Log.e(TAG, "initVideoPath: "+uri);}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults) {switch (requestCode){case 1:if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){initVideoPath();}else{Toast.makeText(this, "拒绝授权则无法使用本APP", Toast.LENGTH_LONG).show();finish();}break;}}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.button_vPlay:if(!videoView.isPlaying()){videoView.start();}break;case R.id.button_vPause:if(videoView.isPlaying()){videoView.pause();}break;case R.id.button_vReplay:if(videoView.isPlaying()){videoView.resume();}break;}}@Overrideprotected void onDestroy() {super.onDestroy();if(videoView != null){videoView.suspend(); // 释放资源}}
}