android97 播放音頻 有進度條控制

來源:互聯網
上載者:User

標籤:

package com.itheima.musicplayer;import android.os.Bundle;import android.os.Handler;import android.os.IBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.view.Menu;import android.view.View;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;public class MainActivity extends Activity {    static Handler handler = new Handler(){//handler是Google說明的定義成靜態,        public void handleMessage(android.os.Message msg) {            Bundle bundle = msg.getData();            int duration = bundle.getInt("duration");            int currentPostition = bundle.getInt("currentPosition");            //重新整理進度條的進度,設定SeekBar的Max和Progress就能夠時時更新SeekBar的長度,            sb.setMax(duration);            sb.setProgress(currentPostition);        }    };        MusicInterface mi;    private MyserviceConn conn;    private Intent intent;    private static SeekBar sb;//屬性在對象產生的時候才有,所以在靜態代碼中要變成靜態。    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sb = (SeekBar) findViewById(R.id.sb);        sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {//SeekBar進度改變事件            @Override            public void onStopTrackingTouch(SeekBar seekBar) {//手指抬起                //拖動SeekBar的進度改變音樂播放進度                int progress = seekBar.getProgress();                //改變播放進度                mi.seekTo(progress);            }            @Override            public void onStartTrackingTouch(SeekBar seekBar) {//手指按下            }            @Override            public void onProgressChanged(SeekBar seekBar, int progress,                    boolean fromUser) {//手指滑動            }        });        intent = new Intent(this, MusicService.class);        startService(intent);        conn = new MyserviceConn();        bindService(intent, conn, BIND_AUTO_CREATE);    }    class MyserviceConn implements ServiceConnection{        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            mi = (MusicInterface) service;//中間人        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    }        public void play(View v){        mi.play();    }    public void continuePlay(View v){        mi.continuePlay();    }    public void pause(View v){        mi.pause();    }    public void exit(View v){        unbindService(conn);  //解除綁定        stopService(intent);  //停止    }}//資訊清單檔:<service android:name="com.itheima.musicplayer.MusicService"></service>/*<SeekBar android:id="@+id/sb"android:layout_width="match_parent"android:layout_height="wrap_content"/>   音樂播放器的進度條,可以拖動改變音樂的播放進度,不同於processBar不可以拖動*/ 
package com.itheima.musicplayer;public interface MusicInterface {    void play();    void pause();    void continuePlay();    void seekTo(int progress);}
package com.itheima.musicplayer;import java.io.IOException;import java.util.Timer;import java.util.TimerTask;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.media.MediaPlayer.OnPreparedListener;import android.os.Binder;import android.os.Bundle;import android.os.IBinder;import android.os.Message;public class MusicService extends Service {    MediaPlayer player;//播放音樂API    private Timer timer;    @Override    public IBinder onBind(Intent intent) {        return new MusicController();    }    class MusicController extends Binder implements MusicInterface{        @Override        public void play() {            MusicService.this.play();        }        @Override        public void pause() {            MusicService.this.pause();        }        @Override        public void continuePlay() {            MusicService.this.continuePlay();        }        @Override        public void seekTo(int progress) {            MusicService.this.seekTo(progress);        }    }        @Override    public void onCreate() {        super.onCreate();        player = new MediaPlayer();    }        @Override    public void onDestroy() {        super.onDestroy();        //停止播放        player.stop();        //釋放佔用的資源,此時player對象已經廢掉了,但是player對象還在。        player.release();        player = null;        if(timer != null){            timer.cancel();            timer = null;        }    }        //播放音樂    public void play(){        //重設        player.reset();        try {            //載入多媒體檔案            player.setDataSource("sdcard/zxmzf.mp3");//            player.setDataSource("http://192.168.13.119:8080/bzj.mp3");//            player.prepare();  因為調用了硬體所以要做準備            player.prepareAsync();   //非同步準備,開啟子線程載入資源//            player.start();            player.setOnPreparedListener(new OnPreparedListener() {//準備監聽                //prepare()方法準備完畢時,此方法調用                @Override                public void onPrepared(MediaPlayer mp) {                    player.start();                    addTimer();                }            });        } catch (Exception e) {            e.printStackTrace();        }     }        //繼續播放    public void continuePlay(){        player.start();    }        //暫停播放    public void pause(){        player.pause();    }        public void seekTo(int progress){        player.seekTo(progress);    }    public void addTimer(){        if(timer == null){            timer = new Timer();//timer就是開啟子線程執行任務,與純粹的子線城不同的是可以控制子線城執行的時間,            timer.schedule(new TimerTask() {                                @Override                public void run() {                    //擷取歌曲總時間長度                    int duration = player.getDuration();                    //擷取歌曲當前播放進度                    int currentPosition= player.getCurrentPosition();                    Message msg = MainActivity.handler.obtainMessage();                    //把進度封裝至訊息對象中                    Bundle bundle = new Bundle();                    bundle.putInt("duration", duration);                    bundle.putInt("currentPosition", currentPosition);                    msg.setData(bundle);                    MainActivity.handler.sendMessage(msg);                }                //開始計時任務後的5毫秒後第一次執行run方法,以後每500毫秒執行一次            }, 5, 500);        }    }}

 

android97 播放音頻 有進度條控制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.