播放多媒体文件(音频,视频)

在安卓上播放多媒体文件是非常常见的,听音乐,看电视等等,接下来,我们就通过一些例子来学习在手机上播放一个简易的音频和视频播放器。

播放音频

别的不多说,直接上代码吧!

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, 
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值