Android MediaPlayer

参考网址

1、https://blog.csdn.net/wangmx1993328/article/details/82798626
2、https://blog.csdn.net/sinat_38892960/article/details/86064461

拷贝音频文件 三种位置

1.在res raw下
在这里插入图片描述
2、在main assets下
在这里插入图片描述
3、在sdcard中
在这里插入图片描述

主界面布局文件

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放"
        android:id="@+id/btn_play"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="暂停"
        android:id="@+id/btn_pause"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止"
        android:id="@+id/btn_stop"/>

    <!--显示当前时间和总时间-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="当前时间"
            android:id="@+id/tv_now"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="总时长"
            android:id="@+id/tv_total"
            android:layout_alignParentRight="true"
            />

    </RelativeLayout>

    <SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0"
        android:id="@+id/seekBar"/>

</LinearLayout>

主界面代码文件

package com.example.demo;

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

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.media.MediaParser;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final int MSG_PLAY = 1001;
    private Button btn_play;
    private Button btn_pause;
    private Button btn_stop;
    private MediaPlayer mediaPlayer;
    private TextView tv_now;
    private TextView tv_total;
    private SeekBar seekBar;
    private Handler handler;
    private int duration;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    private boolean isPauseListener = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initHandler();

        tv_now = findViewById(R.id.tv_now);
        tv_total = findViewById(R.id.tv_total);
        seekBar = findViewById(R.id.seekBar);

        // 检查是否有权限
        verifyStoragePermissions(this);

        btn_play = findViewById(R.id.btn_play);
        btn_pause = findViewById(R.id.btn_pause);
        btn_stop = findViewById(R.id.btn_stop);

        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer == null) {
                    // 第一种 位置在res/raw
                    /*mediaPlayer = MediaPlayer.create(
                            MainActivity.this, R.raw.xiaoqingwa);*/

                    // 第二种 位置在main/assets
                    /**
                    try {
                        AssetFileDescriptor descriptor = getAssets().openFd("shangfeng.aac");
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(descriptor);
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                     */

                    // 第三种 位置在sd卡
                    try {
                        String filePath = "/storage/emulated/0/Pictures/shangfeng.aac";
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(filePath);
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mediaPlayer.start();
                duration = mediaPlayer.getDuration();
                Log.e("mediaPlayer", "duration = " + duration);
                // 将毫秒数转换成 mm:ss格式
                String text =  getTimeStr(duration);
                tv_total.setText(text);
            }
        });

        btn_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer != null){
                    mediaPlayer.pause();
                }
            }
        });

        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer!=null){
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(isPauseListener){
                    return;
                }

                Log.e("seekBar","onProgressChanged");
                int msec = duration * progress / 100;
                mediaPlayer.seekTo(msec);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        // 开一个线程 每隔300毫秒查询当前进度
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if(mediaPlayer != null) {
                        int currentPosition = mediaPlayer.getCurrentPosition();
                        Log.e("mediaPlayer", "currentPosition = " + currentPosition);
                        // 发消息 更新
                        Message message = new Message();
                        message.what = MSG_PLAY;
                        message.arg1 = currentPosition;
                        handler.sendMessage(message);
                    }
                }
            }
        }).start();
    }

    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if(msg.what == MSG_PLAY){
                    // 显示当前时间
                    String text =  getTimeStr(msg.arg1);
                    tv_now.setText(text);

                    // 计算当前的进度
                    int progress = 100 * msg.arg1 / duration;
                    // 在设置进度时 先把listener禁用
                    isPauseListener = true;
                    seekBar.setProgress(progress);
                    // 在设置进度完成时 再把listener起用
                    isPauseListener = false;

                    return true;
                }
                return false;
            }
        });
    }

    /*
    获取时间字符格式
     */
    private String getTimeStr(int duration) {
        int secTotal =  duration / 1000;
        int sec = secTotal % 60;
        int min = secTotal / 60;
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(min);
        stringBuffer.append(":");
        if(sec < 10){
            stringBuffer.append("0");
        }
        stringBuffer.append(sec);
        return stringBuffer.toString();
    }

    /**
     * 检查当前Activity是否有某种权限 没有则弹出授权框
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }
}

使用SoundPool播放音效

如果应用程序经常播放密集、急促而又短暂的音效(如游戏音效)那么使用MediaPlayer显得有些不太适合了。因为MediaPlayer存在如下缺点:

  1. 延时时间较长,且资源占用率高。
  2. 不支持多个音频同时播放。

Android中除了MediaPlayer播放音频之外还提供了SoundPool来播放音效,SoundPool使用音效池的概念来管理多个短促的音效,例如它可以开始就加载20个音效,以后在程序中按音效的ID进行播放。

参考网址:Android开发之SoundPool使用详解

示例代码
package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button btn1;
    private Button btn2;
    private Button btn3;
    private Button btn4;
    private Button btn5;
    private SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 1);
        int wav1 = soundPool.load(MainActivity.this, R.raw.chimes, 1);
        int wav2 = soundPool.load(MainActivity.this, R.raw.ding, 1);
        int wav3 = soundPool.load(MainActivity.this, R.raw.enter, 1);
        int wav4 = soundPool.load(MainActivity.this, R.raw.notify, 1);
        int wav5 = soundPool.load(MainActivity.this, R.raw.ringout, 1);

        btn1 =findViewById(R.id.btn1);
        btn2 =findViewById(R.id.btn2);
        btn3 =findViewById(R.id.btn3);
        btn4 =findViewById(R.id.btn4);
        btn5 =findViewById(R.id.btn5);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soundPool.play(wav1, 1, 1,1,0, 1);
            }
        });
    }
}

使用VideoView组件播放视频

布局文件
<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <VideoView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/videoView"/>

</LinearLayout>
Java代码 实现播放和控制
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {
    private VideoView videoView;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查动态权限
        verifyStoragePermissions(this);

        String filePath = "/sdcard/Movies/family.mp4";

        videoView = findViewById(R.id.videoView);
        videoView.setVideoPath(filePath);
        videoView.start();

        MediaController mediaController = new MediaController(MainActivity.this);
        videoView.setMediaController(mediaController);
    }


    /**
     * 检查当前Activity是否有某种权限 没有则弹出授权框
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }
}
增加文件读写的权限
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
设置界面横屏

在中增加一个属性

<activity android:name=".MainActivity"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

使用MediaPlayer播放视频

布局文件
<?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"
    tools:context=".MainActivity"
    android:orientation="vertical"    >

    <SurfaceView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/surface_view"/>

</LinearLayout>
Java代码
package com.example.mediaplayerdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.MediaController;

public class MainActivity extends AppCompatActivity{
    private MediaPlayer mediaPlayer;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.family);
        surfaceView = findViewById(R.id.surface_view);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                mediaPlayer.setDisplay(holder);
        		mediaPlayer.start();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

            }
        });
    }
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值