最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。
上一篇中我们介绍了如何调用手机的摄像头与打开手机相册,本篇主要讲解一下如何播放本地的音频和视频文件。
1,使用的基本步骤
打开本地音频和本地视频步骤基本上一样,都是操作本地多媒体文件,只是播放的媒介不一样。
(1)播放本地音频文件步骤
- 第一步:初始化一个MediaPlayer实例对象
- 第二步:通过setDataSource()为该实例对象设置数据源
- 第三步:调用该实例对象的start(),pause(),reset()等方法来执行相应的动作
(2)播放本地视频文件步骤
- 第一步:在布局中添加一个播放视频的VideoView控件
- 第二步:初始化该控件实例对象,设置播放视频的路径
- 第三步:调用该实例对象的方法实现播放,暂停,重放;还可以获取视频时长以及配合SeekBar实现进度显示
注:上面两个步骤,我都默认是6.0以下版本,我在代码中做了对比,在播放本地音频文件的时候,我动态申请了读取本地文件权限,而播放本地视频文件我没有动态申请;所以在测试的时候,你可以分别用6.0以下版本模拟器和6.0及以上版本分别测试一下,会发现不一样的现象。(如何动态申请权限请点击查看)
2,示例代码
MainActivity.java代码:
package com.hfut.operationradiofile;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playMusic(View view){
intent=new Intent(this,RadioActivity.class);
startActivity(intent);
}
public void playVideo(View view){
intent=new Intent(this,VideoActivity.class);
startActivity(intent);
}
}
RadioActivity.java代码:
package com.hfut.operationradiofile;
import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
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.Toast;
import java.io.File;
import java.io.IOException;
public class RadioActivity extends AppCompatActivity {
private MediaPlayer musicPlayer=new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
initMusicPlayer();
}
}
//初始化音乐播放器
private void initMusicPlayer() {
File file= new File("/mnt/sdcard/","beyond.mp3");
try {
musicPlayer.setDataSource(file.getPath());
musicPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startPlay(View view){
if(!musicPlayer.isPlaying()) {
musicPlayer.start();
}
}
public void pausePlay(View view) {
if (musicPlayer.isPlaying()) {
musicPlayer.pause();
}
}
//注意停止播放实现
public void stopPlay(View view) {
if (musicPlayer.isPlaying()) {
musicPlayer.reset();
initMusicPlayer();
}
}
@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) {
initMusicPlayer();
} else {
Toast.makeText(this, "你已经拒绝了该权限", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//释放资源
if(musicPlayer!=null){
musicPlayer.stop();
musicPlayer.release();
}
}
}
VideoActivity.java代码:
package com.hfut.operationradiofile;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class VideoActivity extends AppCompatActivity {
private static final String TAG = "VideoActivity";
public static final int PROGRESSINDEX = 1;
public static final int ENDINDEX = 2;
private Timer timer;
private SeekBar progress;
private VideoView screen;
private int length=0;
private TextView showVideoLength;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PROGRESSINDEX:
progress.setProgress(msg.arg1);
showVideoLength.setText((String)msg.obj);
Log.i(TAG, "handleMessage: "+msg.arg1);
break;
case ENDINDEX:
progress.setProgress(msg.arg1);
showVideoLength.setText((String)msg.obj);
Toast.makeText(VideoActivity.this,
"影片放完了,记得分享哟", Toast.LENGTH_SHORT).show();
break;
default:
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
screen = findViewById(R.id.video_screen);
//screen.setBackgroundColor(R.color.colorPrimary);
screen.setBackgroundColor(R.color.transparent);
//可以试试不加下面这一句看看效果(其主要用于设置图层顺序的,其目的是避免继承
// SurfaceView的VideoView出现透明或者黑屏的现象)
screen.setZOrderOnTop(true);
progress = findViewById(R.id.video_progress);
showVideoLength=findViewById(R.id.video_length);
progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Message message=new Message();
if(length-progress>=10000){
message.what = PROGRESSINDEX;
message.arg1 = progress;
message.obj=TimeDealer.getTime(length-progress);
handler.sendMessage(message);
}
else{
message.what = ENDINDEX;
message.arg1 = progress;
message.obj=TimeDealer.getTime(length-progress);
handler.sendMessage(message);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
screen.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
screen.start();
}
});
initVideoPlayer();
}
public void startPlay(View view) {
//screen.setBackgroundColor(R.color.transparent);
//设置视频时长
final int videoLength = screen.getDuration();
length=videoLength;
Log.i(TAG, "startPlay: "+videoLength);
progress.setMax(videoLength);
showVideoLength.setText(TimeDealer.getTime(videoLength));
progress.setProgress(0);
if (!screen.isPlaying()) {
screen.start();
}
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
int currentLength = screen.getCurrentPosition();
if ((videoLength - currentLength) >= 10000) {
Message message = new Message();
message.what = PROGRESSINDEX;
message.arg1 = currentLength;
message.obj=TimeDealer.getTime(videoLength-currentLength);
handler.sendMessage(message);
} else {
Message message = new Message();
message.what = ENDINDEX;
message.arg1 = currentLength;
message.obj=TimeDealer.getTime(videoLength-currentLength);
handler.sendMessage(message);
}
}
}, 0, 1000);
}
public void pausePlay(View view) {
if (screen.isPlaying()) {
screen.pause();
}
}
public void rePlay(View view) {
//设置视频时长
progress.setProgress(0);
if (screen.isPlaying()) {
screen.resume();
} else {
screen.start();
screen.resume();
}
}
private void initVideoPlayer() {
File file = new File("/mnt/sdcard/", "littleApple.mp4");
screen.setVideoPath(file.getPath());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (screen != null) {
screen.suspend();
}
if (timer != null) {
timer.cancel();
}
}
}
TimeDealer.java代码:
package com.hfut.operationradiofile;
/**
* author:why
* created on: 2018/4/9 16:49
* description:
*/
public class TimeDealer {
public static int MORETHANHOUR=60*60*1000;
public static int MORETHANMinute=60*1000;
public static String getTime(int timeLength){
String time=null;
if(timeLength>=MORETHANHOUR){
//自己处理一下
}
else if(timeLength>=MORETHANMinute){
int tempMinute=timeLength/1000/60;
int tempSecond=(timeLength-tempMinute*1000*60)/1000;
if(tempMinute<10){
if(tempSecond<10) {
time = "00:" + "0" + tempMinute + ":"+"0"+tempSecond;
}
else{
time = "00:" + "0" + tempMinute + ":"+tempSecond;
}
}
else{
if(tempSecond<10) {
time = "00:" + tempMinute + ":" + "0" + tempSecond;
}
else{
time = "00:" + tempMinute + ":" + tempSecond;
}
}
}
return time;
}
}
activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.operationradiofile.MainActivity">
<Button
android:layout_marginTop="20dp"
android:onClick="playMusic"
android:text="音乐演示"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:onClick="playVideo"
android:text="视频演示"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
activity_radio.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.operationradiofile.RadioActivity">
<Button
android:layout_marginTop="20dp"
android:onClick="startPlay"
android:text="开始"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:onClick="pausePlay"
android:text="暂停"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:onClick="stopPlay"
android:text="停止"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
activity_video.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.operationradiofile.VideoActivity">
<VideoView
android:id="@+id/video_screen"
android:layout_width="match_parent"
android:layout_height="400dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<SeekBar
android:id="@+id/video_progress"
android:layout_width="530dp"
android:layout_height="30dp"
/>
<TextView
android:id="@+id/video_length"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:gravity="center"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="160dp"
android:layout_marginTop="20dp"
android:onClick="startPlay"
android:text="开始" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="pausePlay"
android:text="暂停" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="rePlay"
android:text="重新播放" />
</LinearLayout>
</LinearLayout>
主配置文件AndroidManifest.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hfut.operationradiofile">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RadioActivity" />
<activity android:name=".VideoActivity">
</activity>
</application>
</manifest>
3,运行结果
注:欢迎扫码关注