1. 程式人生 > >Android視訊音樂播放SeekBar和播放時間同步

Android視訊音樂播放SeekBar和播放時間同步

方案一:使用handler控制SeekBar和時間,以視訊為例

這裡寫圖片描述

佈局檔案XML

<RelativeLayout
        android:id="@+id/video_layout"
        android:layout_width="match_parent"
        android:layout_height="220dp"
        android:layout_below="@+id/videoPlay_name"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart
="true">
<VideoView android:id="@+id/vv_player" android:layout_width="match_parent" android:layout_height="200dp" /> <LinearLayout android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height
="20dp" android:orientation="horizontal" android:weightSum="1">
<TextView android:id="@+id/video_now_time" android:layout_width="wrap_content" android:layout_height="20dp" android:text="00:00:00"/> <SeekBar
android:id="@+id/video_seekBar" android:layout_width="wrap_content" android:layout_height="20dp" android:layout_weight="1.00" />
<TextView android:id="@+id/video_total_time" android:layout_width="wrap_content" android:layout_height="20dp" android:text="00:00:00" /> </LinearLayout> </RelativeLayout> <ImageView android:id="@+id/video_play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/video_layout" android:layout_centerHorizontal="true" android:layout_marginTop="17dp" android:maxHeight="40dp" android:adjustViewBounds="true"/>

JAVA程式碼VideoPlay.java

package com.example.videoplay;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;



public class VideoPlay extends Activity implements View.OnClickListener{

    private VideoView vv_player;
    private TextView videoPlay_name,video_now_time,video_total_time;
    private ImageView play;
    private ImageView back;
    private SeekBar video_seekBar;
    private boolean isPlaying;
    public static final int UPDATE_UI = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_play);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.system));
        }

        /*
            載入佈局
         */
        loadView();

        video_seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int process = seekBar.getProgress();
                if(vv_player != null && vv_player.isPlaying()) {
                    vv_player.seekTo(process);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub

            }
        });
    }
    //更新時間
    private void updateTime(TextView textView,int millisecond){
        int second = millisecond/1000;
        int hh = second / 3600;
        int mm = second % 3600 / 60;
        int ss = second % 60;

        String str = null;
        if(hh!=0){
            str = String.format("%02d:%02d:%02d",hh,mm,ss);
        }else {
            str = String.format("%02d:%02d",mm,ss);
        }

        textView.setText(str);

    }

    private Handler UIhandle = new Handler(){

        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            if(msg.what==UPDATE_UI) {
                int position = vv_player.getCurrentPosition();
                int totalduration = vv_player.getDuration();

                video_seekBar.setMax(totalduration);
                video_seekBar.setProgress(position);

                updateTime(video_now_time,position);
                updateTime(video_total_time,totalduration);

                UIhandle.sendEmptyMessageDelayed(UPDATE_UI, 500);
            }
        }
    };


    //載入整個view檢視,自動播放視訊
    public void loadView(){

        //載入videoview控制元件
        vv_player = (VideoView)findViewById(R.id.vv_player);
        videoPlay_name = (TextView) findViewById(R.id.videoPlay_name);
        play = (ImageView) findViewById(R.id.video_play);
        back = (ImageView) findViewById(R.id.video_back);
        play.setOnClickListener(this);
        back.setOnClickListener(this);
        play.setImageResource(R.drawable.pause);
        back.setImageResource(R.drawable.back);
        video_seekBar = findViewById(R.id.video_seekBar);
        video_now_time = findViewById(R.id.video_now_time);
        video_total_time = findViewById(R.id.video_total_time);

        //設定伺服器視訊資源路徑
        Intent intent = getIntent();
        String address = intent.getStringExtra("address");
        String name = intent.getStringExtra("name");
        videoPlay_name.setText(name);
        Uri uri =  Uri.parse(address);
        vv_player.setVideoURI(uri);
        //設定本地視訊資源路徑
    //  vv_player.setVideoPath("/sdcard/video/test.mp4");
        //MediaController mc = new MediaController(VideoPlay.this);
        //mc.setVisibility(View.INVISIBLE);
        //vv_player.setMediaController(mc);
        //設定焦點
        vv_player.requestFocus();
        //播放
        vv_player.start();

        UIhandle.sendEmptyMessage(UPDATE_UI);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.video_play:
                if(vv_player.isPlaying()){
                    vv_player.pause();
                    play.setImageResource(R.drawable.play);
                }else{
                    vv_player.start();
                    play.setImageResource(R.drawable.pause);
                }
                break;
            case R.id.video_back:
                this.finish();
                break;
        }
    }
}

方案二:使用程序控制SeekBar

JAVA程式碼MusicPlay.java

public class MusicPlay extends Activity implements View.OnClickListener{

    private TextView music_name;
    private ImageView play;
    private SeekBar seekBar;
    private Boolean isplaying;
    private ImageView back;
    private TextView music_now_time,music_total_time;
    private static final int UPDATE_TIME = 2;
    private MediaPlayer mediaPlayer;
    private String url;

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    play.setImageResource(R.drawable.pause);
                    break;
                case UPDATE_TIME:{
                    /**
                     * 更新時間
                     */
                    int position = mediaPlayer.getCurrentPosition();
                    int totalduration = mediaPlayer.getDuration();

                    updateTime(music_now_time,position);
                    updateTime(music_total_time,totalduration);

                    handler.sendEmptyMessageDelayed(UPDATE_TIME, 500);

                }
                    break;


            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_music_play);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.system));
        }
        music_name = (TextView) findViewById(R.id.music_name);
        seekBar = (SeekBar) findViewById(R.id.music_seekBar);
        play = (ImageView) findViewById(R.id.play);
        back = (ImageView) findViewById(R.id.music_back);
        back.setOnClickListener(this);
        play.setOnClickListener(this);

        music_now_time = (TextView) findViewById(R.id.music_now_time);
        music_total_time = (TextView) findViewById(R.id.music_total_time);

        initMediaPlayer();
        initView();

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int process = seekBar.getProgress();
                if(mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(process);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void updateTime(TextView textView,int millisecond){
        int second = millisecond/1000;
        int hh = second / 3600;
        int mm = second % 3600 / 60;
        int ss = second % 60;

        String str = null;
        if(hh!=0){
            str = String.format("%02d:%02d:%02d",hh,mm,ss);
        }else {
            str = String.format("%02d:%02d",mm,ss);
        }

        textView.setText(str);

    }


    private void initView(){
        /**
         * 初始化播放暫停鍵
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }).start();
    }

    private void initMediaPlayer() {

        Intent intent = getIntent();
        url = intent.getStringExtra("address");
        String name = intent.getStringExtra("name");
        music_name.setText(name);

        new Thread(new Runnable() {
            @Override
            public void run() {
                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer = MediaPlayer.create(MusicPlay.this, Uri.parse(url));
                    mediaPlayer.start();
                    handler.sendEmptyMessage(UPDATE_TIME);
                    int max = mediaPlayer.getDuration();
                    seekBar.setMax(max);
                    /**
                    *開啟程序控制SeekBar
                    */
                    new Thread() {
                        public void run() {
                            isplaying = true;
                            while (isplaying) {
                                int position = mediaPlayer.getCurrentPosition();
                                seekBar.setProgress(position);
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }

                        }
                    }.start();

                    mediaPlayer.setLooping(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.play:{
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                    play.setImageResource(R.drawable.play);
                } else{
                    mediaPlayer.start();
                    play.setImageResource(R.drawable.pause);
                }
            }break;
            case R.id.music_back:
                this.finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK,同時沒有重複
            mediaPlayer.stop();
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}