Android MediaPlayer播放raw资源封装类

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

import com.bhuitong.yibaocan.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();
              mPlayer = null;
          }

    }
    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 = MediaPlayer.create(context, GetStringID(text));  //添加本地资源
        mPlayer.setLooping(false);//设置不循环
        mPlayer.start();   //开始播放
    }
    //播放语音
    public void PlaySound(int id)
    {
        if (mPlayer!=null){  //判断当mPlayer不为空的时候
            mPlayer.stop();  //先结束上一个播放内容
        }
        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");//根据自己实际资源编写

猜你喜欢

转载自www.cnblogs.com/zhaogaojian/p/10128827.html
今日推荐