其他分享
首页 > 其他分享> > Android MediaPlayer 播放音频文件工具方法

Android MediaPlayer 播放音频文件工具方法

作者:互联网

MediaPlayer player = null;
public static void playVoice(String filepath,boolean is_local){
try{
player = new MediaPlayer();
if (!is_local) {//是否为本地录音文件
AssetFileDescriptor fd = getActivity().getAssets().openFd();//access目录下录音名称即文件名
player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
} else {
player.setDataSource(filepath);//本地录音全路径
}
player.setVolume(1, 1);
if (!player.isPlaying()) {
player.prepareAsync();
}
// 当 MediaPlayer调用prepare()方法时触发该监听器。
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
//为 Media Player的播放完成事件绑定事件监听器。
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub

            }
        });
}catch(Exception e){
         e.printStackTrace();
 }

}

//停止播放
public void stopPlay() {
if (player != null) {
try {
player.stop();
} catch (Exception e) {
e.printStackTrace();
player = null;
player = new MediaPlayer();
player.stop();
}
player.release();
player = null;
}
}

标签:MediaPlayer,void,音频文件,player,new,Android,null,public
来源: https://blog.csdn.net/and_bjdbc/article/details/116303282