MediaPlayer.prepareAsync();遇到的問題

最近在一直在弄畢設(shè),是一個(gè)音樂播放器训措。使用的是原生的MediaPlayer,下面是開原地址:https://github.com/Andy-86/FantasticPlayer

image.png

因?yàn)橐婚_始是播放本地音樂,所以一直使用MediaPlayer.prepare();但當(dāng)播放在線音樂的時(shí)候會(huì)出現(xiàn)阻塞芹啥,所以使用MediaPlayer.prepareAsync();,但是有時(shí)候會(huì)發(fā)生錯(cuò)誤(-38,0)铺峭。最后查閱官方文檔才發(fā)現(xiàn)當(dāng)再Prepare的時(shí)候假如有stop()墓怀,start(),setDataSource()卫键,seekTo(progress)傀履,pause(),getCurrentPosition();等都會(huì)報(bào)錯(cuò)永罚,所以要像中斷操作只能使用reset()方法啤呼。

下面是我的Mediaplayer的Service的代碼,我是通過AIDl進(jìn)行控制和將信息廣播出去呢袱,由于ADIL運(yùn)行在Binder線程池里面 使用都是用了synchronize來同步官扣。

public class MusicService extends Service implements MediaPlayer.OnErrorListener,
        MediaPlayer.OnPreparedListener,
        MediaPlayer.OnCompletionListener,
        AudioManager.OnAudioFocusChangeListener {

    public static final int MUSIC_ACTION_PLAY = 0xff001;
    public static final int MUSIC_ACTION_LAST = 0xff002;
    public static final int MUSIC_ACTION_NEXT = 0xff003;
    public static final int MUSIC_ACTION_PAUSE = 0xff004;
    public static final int MUSIC_ACTION_STOP = 0xff005;
    public static final int MUSIC_ACTION_CONTINUE_PLAY = 0xff006;
    public static final int MUSIC_ACTION_SEEK_PLAY = 0xff007;
    public static final int MUSIC_ACTION_COMPLETE = 0xff008;
    public static final  int MUSIC_ACTION_ERROR=0xff009;
    public static final String SONGBEAN="Songbean";
    private RemoteCallbackList<MusicPlayListner> remoteCallbackList = new RemoteCallbackList<>();
    private Timer timer;
    private static final String TAG="MusicService";
    private SongBean songBean;
    @Override
    public void onCreate() {
        init();
        super.onCreate();
    }

    private IBinder mybinder = new IMusicPlayer.Stub()

    {

        @Override
        public void action(int actioncode, SongBean songBean) throws RemoteException {
            switch (actioncode) {
                case MUSIC_ACTION_PLAY:
                    String path;
                    setSongBean(songBean);
                    if(songBean.getM4a()!=null)
                        path = songBean.getM4a();
                    else
                         path = songBean.getPath();
                    playSong(path);
                    LogUtil.doLog("String path", "paly:" + path);
                    Message msg=Message.obtain();
                    msg.what=MUSIC_ACTION_PLAY;
                    sendMessge(MUSIC_ACTION_PLAY,msg);
                    break;
                case MUSIC_ACTION_PAUSE:
                    pauseSong();
                    LogUtil.doLog("action", "pause");
                    Message msg2=Message.obtain();
                    msg2.what=MUSIC_ACTION_PAUSE;
                    sendMessge(MUSIC_ACTION_PAUSE,msg2);
                    break;
                case MUSIC_ACTION_STOP:
                    stopSong();
                    break;
                case MUSIC_ACTION_LAST:
                    stopSong();
                    setSongBean(songBean);
                    String path2 = (String) songBean.getM4a();
                    playSong(path2);
                    break;
                case MUSIC_ACTION_NEXT:
                    stopSong();
                    setSongBean(songBean);
                    String path3 = (String) songBean.getM4a();
                    playSong(path3);
                    break;
                case MUSIC_ACTION_CONTINUE_PLAY:
                    continuePlaySong();
                    LogUtil.doLog("action", "continue play");
                    Message msg3=Message.obtain();
                    msg3.what=MUSIC_ACTION_CONTINUE_PLAY;
                    sendMessge(MUSIC_ACTION_CONTINUE_PLAY,msg3);
                    break;
                case MUSIC_ACTION_SEEK_PLAY:
                    int progerss=songBean.getProgress();
                    seekPlaySong(progerss);
                    break;


            }
        }

        @Override
        public void registListner(MusicPlayListner listner) throws RemoteException {
            remoteCallbackList.register(listner);
        }

        @Override
        public void unregistListner(MusicPlayListner listner) throws RemoteException {
            remoteCallbackList.unregister(listner);
        }
    };

    public MusicService() {
    }

    private MediaPlayer mMediaPlayer;
    private MediaPlayer onlinePlayer;
    private Handler handler;

    public void init() {
        handler = new Handler();
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        ((AudioManager) getSystemService(Context.AUDIO_SERVICE)).
                requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }

    public void initOnlinePlyer(){
        onlinePlayer=new MediaPlayer();
        onlinePlayer.setOnErrorListener(this);
        onlinePlayer.setOnPreparedListener(this);
        onlinePlayer.setOnCompletionListener(this);
    }

    @Override
    public void onAudioFocusChange(int focusChange) {

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Message msg=Message.obtain();
        msg.what=MUSIC_ACTION_COMPLETE;
        sendMessge(MUSIC_ACTION_COMPLETE,msg);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        LogUtil.doLog("onError",""+what+extra);
        if(songBean.getM4a()!=null) {
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            bundle.putParcelable("SongBean", songBean);
            message.setData(bundle);
            message.what = MUSIC_ACTION_ERROR;
            sendMessge(MUSIC_ACTION_ERROR, message);
        }
        mMediaPlayer.reset();
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mMediaPlayer.start();
        if (timer == null)
            timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                updateProgress();
            }
        },0, 1000);
    }

    /**
     * 更新進(jìn)度
     */
    private synchronized void updateProgress() {
        if(mMediaPlayer.isPlaying()) {
            Message msg = Message.obtain();
            msg.arg1 = mMediaPlayer.getCurrentPosition();
            msg.arg2 = mMediaPlayer.getDuration();
            msg.what = MUSIC_ACTION_SEEK_PLAY;
            LogUtil.doLog("updateProgress", "" + mMediaPlayer.getCurrentPosition());
            sendMessge(MUSIC_ACTION_PLAY, msg);
        }
    }

    /**
     * 向訂閱的Listner發(fā)送Message
     *
     * @param msg
     */
    private synchronized void sendMessge(int action,Message msg) {
        int n = remoteCallbackList.beginBroadcast();
        for (int i = 0; i < n; i++) {
            MusicPlayListner listner = remoteCallbackList.getBroadcastItem(i);
            try {
                listner.action(action, msg,songBean);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        remoteCallbackList.finishBroadcast();
    }

    public synchronized void playSong(String path) {
        try {
            if(songBean.getM4a()!=null)
            {
                Uri uri=Uri.parse(path);
                mMediaPlayer.reset();//idle
                mMediaPlayer.setDataSource(this,uri);
                mMediaPlayer.prepareAsync();
                return;
            }
            mMediaPlayer.reset();//idle
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepareAsync();


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public synchronized void stopSong() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
        }

    }

    public synchronized void seekPlaySong(int progress) {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.seekTo(progress);
        }
    }

    public synchronized void pauseSong() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();


        }
    }

    public synchronized void continuePlaySong() {
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();


        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogUtil.doLog("onBind", "return  binder-------------------");
        return mybinder;
    }


    public void setSongBean(SongBean songBean) {
        this.songBean = songBean;
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市羞福,隨后出現(xiàn)的幾起案子惕蹄,更是在濱河造成了極大的恐慌,老刑警劉巖治专,帶你破解...
    沈念sama閱讀 211,743評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件卖陵,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡张峰,警方通過查閱死者的電腦和手機(jī)泪蔫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,296評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來喘批,“玉大人撩荣,你說我怎么就攤上這事∪纳睿” “怎么了餐曹?”我有些...
    開封第一講書人閱讀 157,285評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)敌厘。 經(jīng)常有香客問我台猴,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,485評(píng)論 1 283
  • 正文 為了忘掉前任饱狂,我火速辦了婚禮曹步,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘嗡官。我一直安慰自己箭窜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,581評(píng)論 6 386
  • 文/花漫 我一把揭開白布衍腥。 她就那樣靜靜地躺著磺樱,像睡著了一般。 火紅的嫁衣襯著肌膚如雪婆咸。 梳的紋絲不亂的頭發(fā)上竹捉,一...
    開封第一講書人閱讀 49,821評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音尚骄,去河邊找鬼块差。 笑死,一個(gè)胖子當(dāng)著我的面吹牛倔丈,可吹牛的內(nèi)容都是我干的憨闰。 我是一名探鬼主播,決...
    沈念sama閱讀 38,960評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼需五,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼鹉动!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起宏邮,我...
    開封第一講書人閱讀 37,719評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤泽示,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后蜜氨,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體械筛,經(jīng)...
    沈念sama閱讀 44,186評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,516評(píng)論 2 327
  • 正文 我和宋清朗相戀三年飒炎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了埋哟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,650評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡郎汪,死狀恐怖赤赊,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情怒竿,我是刑警寧澤,帶...
    沈念sama閱讀 34,329評(píng)論 4 330
  • 正文 年R本政府宣布扩氢,位于F島的核電站耕驰,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏录豺。R本人自食惡果不足惜朦肘,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,936評(píng)論 3 313
  • 文/蒙蒙 一饭弓、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧媒抠,春花似錦弟断、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,757評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至苍匆,卻和暖如春刘急,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背浸踩。 一陣腳步聲響...
    開封第一講書人閱讀 31,991評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工叔汁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人检碗。 一個(gè)月前我還...
    沈念sama閱讀 46,370評(píng)論 2 360
  • 正文 我出身青樓据块,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親折剃。 傳聞我的和親對(duì)象是個(gè)殘疾皇子另假,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,527評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容