Android MediaPlayer播放本地音频

reference:
《Android 第一行代码》

MediaPlayer类常用的方法:
		setDataSource() 设置要播放的音频文件的路径
		prepare()		开始播放之前调用这个方法完成准备工作
		start()			开始或继续播放
		pause()			暂停播放
		reset()			把MediaPlayer对象重置为刚刚创建的状态
		seekTo()		从指定位置开始播放音频
		stop()			停止播放音频。调用这个方法后的MediaPlayer对象无法再播放音频
		release()		释放掉与MediaPlayer对象相关的资源
		isPlaying()		判断当前MediaPlayer是否正在播放音频
		getDuration()	获取载入的音频文件时长

本demo在Android10.0 华为真机上调试通过,经供参考

开发中遇到权限问题参考了:https://blog.csdn.net/qq_35597100/article/details/107979935
https://blog.csdn.net/zk2000416/article/details/106629555/

布局文件 (三个Button)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play" />

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pause" />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop" />
</LinearLayout>

AndroidManifest.xml(添加权限)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.playaudiotest">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE " />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:requestLegacyExternalStorage="true"
        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>
    </application>

</manifest>

MainActivity.java

package com.android.playaudiotest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = "MainActivity";

    private MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button play = (Button) findViewById(R.id.play);
        Button pause = (Button) findViewById(R.id.pause);
        Button stop = (Button) findViewById(R.id.stop);
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        stop.setOnClickListener(this);
        Log.d(TAG, "onCreate: ");
        //检查权限、申请权限
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else {
            initMediaPlayer();
        }


    }

    private void initMediaPlayer() {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
                "1.mp3"); // storage/sdcard0/1.mp3

        try {
            Log.d(TAG, "initMediaPlayer: " + file.getPath());
            mediaPlayer.setDataSource(file.getPath()); // 指定音频文件的路径
            mediaPlayer.prepare(); // 让MediaPlayer进入准备状态
            Log.d(TAG, "initMediaPlayer: out");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            Log.i(TAG, "用户拒绝了1");
                            Toast.makeText(this,
                                    "拒绝权限将无法使用这个程序1", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                    Log.i(TAG, "用户同意了");
                    initMediaPlayer();
                }else{
                    Log.i(TAG, "用户拒绝了2");
                    Toast.makeText(this,
                            "拒绝权限将无法使用这个程序2", Toast.LENGTH_SHORT).show();
                    finish();
                }
              /*  if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initMediaPlayer();
                } else {
                    Toast.makeText(this,
                            "拒绝权限将无法使用这个程序", Toast.LENGTH_SHORT).show();
                    finish();
                }*/
                break;
            default:

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                Log.d(TAG, "onClick: play");
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();  // 开始播放
                }
                break;
            case R.id.pause:
                Log.d(TAG, "onClick: pause");
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();  // 暂停播放
                }
                break;
            case R.id.stop:
                Log.d(TAG, "onClick: stop");
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.reset(); // 停止播放
                    initMediaPlayer();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值