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

本文详细介绍了在Android中如何实现音频和视频播放。对于音频播放,创建了一个包含播放、暂停和停止按钮的界面,使用MediaPlayer加载SD卡上的.mp3文件。视频播放同样使用VideoView组件,步骤与音频类似,需要预先在SD卡根目录下放置.mp4视频文件,并处理播放、暂停和重播操作。记得在AndroidManifest.xml中添加写外部存储权限。
摘要由CSDN通过智能技术生成

播放音频

1.新建一个项目,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>

在页面布局中我们存放了三个按钮,分别是:播放按钮,暂停按钮和停止按钮

2.现在写MainActivity里的代码

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

          																												 // 点击事件分开写的办法

public class Main2Activity extends AppCompatActivity implements View.OnClickListener {

private MediaPlayer mediaPlayer = new MediaPlayer();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Button play = (Button)findViewById(R.id.play);
    Button pause =(Button)findViewById(R.id.pause);
    Button stop = (Button)findViewById(R.id.stop);
    play.setOnClickListene
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值