Android 音乐播放的管理

来源:互联网 发布:分布式数据库和集群 编辑:程序博客网 时间:2024/06/04 18:37
/** * 音乐播放器的管理类,需要与Activity 的生命周期 * 相联动 * @author Administrator * */public class MediaManager {    private static MediaPlayer mMediaPlayer;    //是否暂停    private static boolean isPause;    /**     * 播放声音     */    public static void playSound(String path,              MediaPlayer.OnCompletionListener listener){          if(mMediaPlayer==null){              mMediaPlayer=new MediaPlayer();              ///错误的监听              mMediaPlayer.setOnErrorListener(new OnErrorListener() {                @Override                public boolean onError(MediaPlayer arg0, int arg1, int arg2) {                    mMediaPlayer.reset();                    return false;                }            });          }else{              //重置              mMediaPlayer.reset();          }     try {         mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);         mMediaPlayer.setOnCompletionListener(listener);         mMediaPlayer.setDataSource(path);         mMediaPlayer.prepare();         mMediaPlayer.start();    } catch (Exception e) {        // TODO 自动生成的 catch 块        e.printStackTrace();    }    }    /**     * 暂停     */    public static void pause(){        if(mMediaPlayer!=null &&mMediaPlayer.isPlaying()){            mMediaPlayer.pause();            isPause=true;        }    };    /**     * 恢复状态     */    public static void reSume(){        if(mMediaPlayer!=null && isPause){            mMediaPlayer.start();            isPause=false;        }    }    /**     * 释放资源     */    public static void release(){        if(mMediaPlayer!=null){            mMediaPlayer.release();            mMediaPlayer=null;        }    }}
0 0
原创粉丝点击