在安卓上播放多媒体文件是非常常见的,听音乐,看电视等等,接下来,我们就通过一些例子来学习在手机上播放一个简易的音频和视频播放器。
播放音频
别的不多说,直接上代码吧!
activity_main.xml代码
<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=".MainActivity">
<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="播放" />
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="暂停" />
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止" />
</LinearLayout>
布局文件中我们放了三个按钮,分别用于播放音频,暂停音频和停止音频。
MainActivity.java代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MediaPlayer mp= new MediaPlayer();//MediaPlayer 实例
private Button play;
private Button pause;
private Button stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = findViewById(R.id.play);//播放按钮
pause = findViewById(R.id.pause);//暂停按钮
stop = 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();
}
}
//请求权限后的回调
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,