Android MediaPlayer

这里写自定义目录标题

    • 参考网址
      • 拷贝音频文件 三种位置
      • 主界面布局文件
      • 主界面代码文件
      • 使用SoundPool播放音效
      • 使用VideoView组件播放视频
        • 布局文件
        • Java代码 实现播放和控制
        • 增加文件读写的权限
        • 设置界面横屏
      • 使用MediaPlayer播放视频
        • 布局文件
        • Java代码

参考网址

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

拷贝音频文件 三种位置

1.在res raw下
Android MediaPlayer_第1张图片
2、在main assets下
Android MediaPlayer_第2张图片
3、在sdcard中
Android MediaPlayer_第3张图片

主界面布局文件


<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播放音效

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组件播放视频

布局文件


<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播放视频

布局文件


<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) {
     

            }
        });
    }
}

你可能感兴趣的:(Android MediaPlayer)