Android MediaPlayer播放raw资源封装类

import android.content.Context;
import android.media.MediaPlayer;

import xxxx.R;

public class MediaUtil {
    MediaPlayer mPlayer=null;
    Context context;
    public MediaUtil(Context context){
        this.context=context;
    }
    //释放
    public void Release()
    {
          if (mPlayer != null && mPlayer.isPlaying()) {
              mPlayer.stop();
              mPlayer.release();          }

    }
    public int GetStringID(String str)
    {
        if(str=="xxxxx")return R.raw.xxxx;///下面把要写的rawid 复制粘贴到此处
            }
    //播放语音
    public void PlaySound(String text)
    {
        if (mPlayer!=null){  //判断当mPlayer不为空的时候
            mPlayer.stop();  //先结束上一个播放内容
mPlayer.Release();
} mPlayer = MediaPlayer.create(context, GetStringID(text)); //添加本地资源 mPlayer.setLooping(false);//设置不循环 mPlayer.start(); //开始播放 } //播放语音 public void PlaySound(int id) { if (mPlayer!=null){ //判断当mPlayer不为空的时候 mPlayer.stop(); //先结束上一个播放内容
      
             mPlayer.Release();

} mPlayer = MediaPlayer.create(context, id); //添加本地资源 mPlayer.setLooping(false);//设置不循环 mPlayer.start(); //开始播放 } public int getResource(String resName){ int resId = context.getResources().getIdentifier(resName,"raw",context.getPackageName()); return resId; } }

 使用方法

1、MediaUtil mediaUtil;

 OnCreate中

2、mediaUtil= new MediaUtil(this);

OnDestory中

3、mediaUtil.Release();

调用地方:

4、mediaUtil.PlaySound("xxx");//根据自己实际资源编写

后续:同事在使用过程中发现有时会没有声音,这里最好改成单例模式。
posted @ 2018-12-16 22:12  zhaogaojian  阅读(677)  评论(0编辑  收藏  举报