Android Open Source - AdvancedPlayer Advanced Player






From Project

Back to project page AdvancedPlayer.

License

The source code is released under:

Apache License

If you think the Android project AdvancedPlayer listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.huilan.library_videoplay;
/*from  w w w .  j  ava 2  s . co m*/
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.huilan.library_videoplay.util.LightnessController;
import com.huilan.library_videoplay.util.ParseHtmlToUrl;
import com.huilan.library_videoplay.util.ViewController;
import com.huilan.library_videoplay.view.SuperVideoView;

import java.io.File;
import java.util.Formatter;
import java.util.Locale;

/**
 * ??SurfaceView??????,???
 * path:?????
 * ????????  0--255
 * ?????  0--15
 */
public class AdvancedPlayer extends Activity implements OnClickListener, SuperVideoView.PlayController, SeekBar.OnSeekBarChangeListener {
    private int state;
    private int screenWidth;
    private int screenHeight;
    private int minMetrics;
    private int mWhich;
    private int maxVolume;
    private int initializeVoice;
    private int initializeLight;
    private int lastVolume;
    private float startX;
    private float startY;
    public boolean isDebug;
    private boolean isShow = true;
    private boolean isClick = true;
    private boolean isStartController;
    private boolean isFullScreen;
    private boolean isLoading = true;
    private boolean screenLockStat = false;
    private AudioManager mAudioManager;
    /**
     * ??????????
     */
    private ImageButton playOrPause;
    private SuperVideoView superVideoView;
    private SeekBar progress;
    private TextView videoName;
    private TextView nowTime;
    private TextView totalTime;
    private StringBuilder mFormatBuilder;
    private Formatter mFormatter;
    private View videoTop;
    private View videoBottom;
    /**
     * 0:??,1:??,2:??????
     */
    private ViewController viewControllerLight;
    private ViewController viewControllerVolume;
    private ImageButton unlockScreen;
    private View loadingView;
    private int currentProgress ;
    private String TAG = "AdvancedPlayer>>";
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 100:
                    autoShowOrHide();
                    break;
                case 99:
                    unlockScreen.setVisibility(View.GONE);
                    break;
                case 98:
                    String videoUrl = (String) msg.obj;
                    if (isVideo(videoUrl)) {
                        videoName.setText(getFileNameWithoutExtension(videoUrl));
                        startVideo(Uri.encode(videoUrl, "@#&=*+-_.,:!?()/~'%"));
                    } else {
                        if (isDebug()) {
                            Log.i("VideoViewPlay", "video play url = " + videoUrl);
                        }
                        Toast.makeText(getApplicationContext(), getString(R.string.video_urlerror), Toast.LENGTH_SHORT).show();
                        AdvancedPlayer.this.finish();
                    }
                    break;
            }
        }
    };
    private boolean lastPlaying;
    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (screenLockStat) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    showLock();
                }
                return false;
            }
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    handler.removeMessages(100);
                    startX = event.getX();
                    startY = event.getY();
                    if (startX > screenWidth / 2) {
                        mWhich = 1;
                    } else {
                        mWhich = 0;
                    }
                    isStartController = false;
                    lastVolume = initializeVoice = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    initializeLight = LightnessController.getLightness(getApplicationContext());
                    currentProgress = superVideoView.getCurrentProgress();
                    break;
                case MotionEvent.ACTION_MOVE:

                    float currentX = event.getX();
                    float currentY = event.getY();
                    float deltaX;
                    float deltaY;
                    if (isStartController) {
//                        deltaX = startX - currentX;
                        deltaX = currentX - startX;
                        deltaY = startY - currentY;
                        if (mWhich == 0) {
                            lightChange(deltaY);
                        } else if (mWhich == 1) {
                            volumeChange(deltaY);
                        } else if (mWhich == 2) {
                            // ??or??
                            if (superVideoView.isPlaying()) {
                                lastPlaying =true;
                                superVideoView.pause();
                            }else {
                                lastPlaying=false;
                            }
                            if(!isShow){
                                autoShowOrHide();
                            }
                            forwardOrRewind(deltaX);
                        }
                    } else {
                        deltaX = startX - currentX;
                        deltaY = startY - currentY;
//                        float absDeltaY = Math.abs(deltaY);
//                        if (absDeltaY > minMetrics) {
//                            isStartController = true;
//                            isClick = false;
//                        } else {
//                            isClick = true;
//                        }
//                        double deltaRel = Math.hypot(deltaX, deltaY);
                        if (Math.hypot(deltaX, deltaY) > minMetrics) {
                            startX=currentX;
                            startY=currentY;
                            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                                mWhich = 2;
                            }
                            isStartController = true;
                            isClick = false;
                        } else {
                            isClick = true;
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    isStartController = false;
                    if (isClick) {
                        autoShowOrHide();
//                        if (isShow) {
//                            handler.sendEmptyMessageDelayed(100, 5000);
//                        }
                    }else {
                        if(mWhich==2){
                            if (lastPlaying&&!superVideoView.isPlaying()) {
                                superVideoView.start();
                                lastPlaying=false;
                            }
                        }
                    }
                    break;
            }
            return true;
        }
    };
    /**
     * ??????
     *
     * @param deltaX ????????????
     */
    private void forwardOrRewind(float deltaX) {
//        int currentProgress = superVideoView.getCurrentProgress();
        if(currentProgress<1500){
            return;
        }
        float deltaTime=deltaX/8f;
        superVideoView.seekTo(currentProgress + (int)(deltaTime * 1000));
//        if (deltaX > 0) {
//            superVideoView.seekTo(currentProgress + (int)(deltaTime * 1000));
//        } else {
//            superVideoView.seekTo(currentProgress - (int)(deltaTime * 1000));
//        }
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        if (screenLockStat) {
//            return true;
//        }
//        return super.onTouchEvent(event);
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_advancedplayer);
        isDebug = isDebug();
//        String url = getIntent().getStringExtra("url");
//        if (TextUtils.isEmpty(url)) {
//            if (isDebug) {
//                Log.i(TAG, "video play url = " + url);
//            }
//            Toast.makeText(getApplicationContext(), getString(R.string.video_urlerror), Toast.LENGTH_SHORT).show();
//            return;
//        }
//        videoName.setText(getFileNameWithoutExtension(url));
//        url = Uri.encode(url, "@#&=*+-_.,:!?()/~'%");
        initView();

        Intent intent = getIntent();
        final String path = intent.getStringExtra("url");
        final String regex = intent.getStringExtra("regex");
        if (isVideo(path)) {
            videoName.setText(getFileNameWithoutExtension(path));
            startVideo(Uri.encode(path, "@#&=*+-_.,:!?()/~'%"));
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String videoUrl = new ParseHtmlToUrl().getVideoUrl(Uri.encode(path, "@#&=*+-_.,:!?()/~'%"), regex);
                    Message msg = Message.obtain();
                    msg.what = 98;
                    msg.obj = videoUrl;
                    handler.sendMessage(msg);
                }
            }).start();
        }

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        minMetrics = (int) (20 * displayMetrics.density + 0.5f);

        if (LightnessController.isAutoBrightness(getApplicationContext())) {
            LightnessController.stopAutoBrightness(getApplicationContext());
        }
        initializeVoice = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        initializeLight = LightnessController.getLightness(getApplicationContext());
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        handler.sendEmptyMessageDelayed(100, 3000);
        if (isDebug)
            Log.i(TAG, screenWidth + "," + screenHeight + "," + minMetrics + "," + initializeLight + "," + initializeVoice);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LightnessController.startAutoBrightness(getApplicationContext());
        if (superVideoView != null) {
            superVideoView.onDestroy();
            superVideoView = null;
        }
        if (viewControllerVolume != null) {
            viewControllerVolume.cancel();
            viewControllerVolume = null;
        }
        if (viewControllerLight != null) {
            viewControllerLight.cancel();
            viewControllerLight = null;
        }

    }

    private boolean isDebug() {
        return (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    }

    /**
     * ????????????????,???????isDebug????????????
     *
     * @param isDebug true ????debug??
     */
    public void setDebug(boolean isDebug) {
        this.isDebug = isDebug;
    }

    private void initView() {
        superVideoView = (SuperVideoView) findViewById(R.id.vv_video_view);
        findViewById(R.id.btn_back).setOnClickListener(this);
        progress = (SeekBar) findViewById(R.id.seekBar_progress);

        unlockScreen = (ImageButton) findViewById(R.id.iBtn_unlock);
        findViewById(R.id.iBtn_lock).setOnClickListener(this);
        findViewById(R.id.iBtn_rewind).setOnClickListener(this);
        playOrPause = (ImageButton) findViewById(R.id.iBtn_playOrPause);
        findViewById(R.id.iBtn_forward).setOnClickListener(this);
        findViewById(R.id.iBtn_fullscreen).setOnClickListener(this);

        videoName = (TextView) findViewById(R.id.tv_name);
        nowTime = (TextView) findViewById(R.id.tv_nowTime);
        totalTime = (TextView) findViewById(R.id.tv_totalTime);

        loadingView = findViewById(R.id.pb_loadingProgressBar);

        unlockScreen.setOnClickListener(this);
        playOrPause.setOnClickListener(this);

        progress.setOnSeekBarChangeListener(this);

        videoTop = findViewById(R.id.in_videoTop);
        videoBottom = findViewById(R.id.in_videoBottom);

        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

        progress.setMax(1000);
        superVideoView.setOnTouchListener(touchListener);
    }

    private boolean isVideo(String url) {
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(getApplicationContext(), getString(R.string.video_urlerror), Toast.LENGTH_SHORT).show();
            return false;
        }
        String fe = getFileExtension(url);
        fe = fe.toLowerCase();
        if (fe.equals("flv") || fe.equals("mp4") || fe.equals("3gp") || fe.equals("fla")
                || fe.equals("wav") || fe.equals("wmv") || fe.equals("avi")
                || fe.equals("rm") || fe.equals("rmvb") || fe.equals("mov")) {
            return true;
        } else {
            return false;
        }

    }

    public String getFileNameWithoutExtension(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }

        int ePosition = filePath.lastIndexOf(".");
        int fPosition = filePath.lastIndexOf(File.separator);
        if (fPosition == -1) {
            return (ePosition == -1 ? filePath : filePath.substring(0, ePosition));
        }
        if (ePosition == -1) {
            return filePath.substring(fPosition + 1);
        }
        return (fPosition < ePosition ? filePath.substring(fPosition + 1, ePosition) : filePath.substring(fPosition + 1));
    }

    private void startVideo(String url) {
        superVideoView.setOnProgressListener(this);

        superVideoView.setVideoPath(url);

        superVideoView.start();
    }

    private String getFileExtension(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }
        int ePosition = filePath.lastIndexOf(".");
        int fPosition = filePath.lastIndexOf(File.separator);
        if (ePosition == -1) {
            return "";
        }
        return (fPosition >= ePosition) ? "" : filePath.substring(ePosition + 1);
    }

    @Override
    public void onClick(View v) {
        handler.removeMessages(100);
        if (isShow) {
            handler.sendEmptyMessageDelayed(100, 5000);
        }
        int i = v.getId();
        if (i == R.id.btn_back) {
            this.finish();
        } else if (i == R.id.iBtn_playOrPause) {
            if (superVideoView.isPlaying()) {
                superVideoView.pause();
                playOrPause.setImageResource(android.R.drawable.ic_media_play);
            } else {
                superVideoView.start();
                playOrPause.setImageResource(android.R.drawable.ic_media_pause);
            }
        } else if (i == R.id.iBtn_lock) {
            Toast.makeText(getApplicationContext(), "????", Toast.LENGTH_SHORT).show();
            screenLockStat = true;
            showLock();
            handler.removeMessages(100);
            if (isShow) {
                autoShowOrHide();
            }
        } else if (i == R.id.iBtn_rewind) {
            int currentProgress = superVideoView.getCurrentProgress();
            superVideoView.seekTo(currentProgress - 6 * 1000);
        } else if (i == R.id.iBtn_forward) {
            int currentProgress = superVideoView.getCurrentProgress();
            superVideoView.seekTo(currentProgress + 6 * 1000);

        } else if (i == R.id.iBtn_fullscreen) {
            Toast.makeText(getApplicationContext(), "???", Toast.LENGTH_SHORT).show();
            if (isFullScreen) {
                setFullScreen(false);
            } else {
                setFullScreen(true);
            }
            isFullScreen = !isFullScreen;
        } else if (i == R.id.iBtn_unlock) {
            screenLockStat = false;
            unlockScreen.setVisibility(View.GONE);
        }
    }

    private void showLock() {
        handler.removeMessages(99);
        if (View.VISIBLE != unlockScreen.getVisibility()) {
            unlockScreen.setVisibility(View.VISIBLE);
            handler.sendEmptyMessageDelayed(99, 3000);
        }
    }

    /**
     * ????????????????
     */
    private synchronized void autoShowOrHide() {
        if (state != 0) {
            return;
        }
        Animation topAnimation;
        Animation bottomAnimation;
        if (isShow) {//??
            isFullScreen = true;
            topAnimation = animationFactory(0, 0, 0, -1, 500);
            bottomAnimation = animationFactory(0, 0, 0, 1, 500);
        } else {//??
            isFullScreen = false;
            topAnimation = animationFactory(0, 0, -1, 0, 500);
            bottomAnimation = animationFactory(0, 0, 1, 0, 500);
            handler.sendEmptyMessageDelayed(100, 5000);
        }
        isShow = !isShow;
        topAnimation.setFillAfter(true);
        bottomAnimation.setFillAfter(true);
        topAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                state += 1;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                if (!isShow) {
//                    setFullScreen(isFullScreen);
//                }
                state -= 1;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        bottomAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                state += 1;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                state -= 1;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


        videoTop.startAnimation(topAnimation);
        videoBottom.startAnimation(bottomAnimation);
//        if (isShow) {
//            setFullScreen(isFullScreen);
//        }
    }

    public void setFullScreen(boolean enable) {
        if (enable) {
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    private Animation animationFactory(float fromX, float toX, float fromY, float toY, int duration) {
        Animation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, fromX, Animation.RELATIVE_TO_SELF,
                toX, Animation.RELATIVE_TO_SELF, fromY, Animation.RELATIVE_TO_SELF, toY);
        animation.setDuration(duration);
        return animation;
    }

    /**
     * ????????????????
     *
     * @param name ?????????
     */
    public void setVideoName(CharSequence name) {
        videoName.setText(name);
    }

    private int lastTotal=0;
    @Override
    public void currentProgress(int current, int total) {
//        Log.i("hehe",current+"-"+total);
        if (current > 0 && current < total-200) {
            if(lastTotal!=total) {
                progress.setMax(total);
                lastTotal=total;
            }
            progress.setProgress(current);
            int bufferPercentage = superVideoView.getBufferPercentage();
            progress.setSecondaryProgress(bufferPercentage * total / 100);
            nowTime.setText(stringForTime(current));
            totalTime.setText(stringForTime(total));
            if (isLoading) {
                loadingView.setVisibility(View.GONE);
                isLoading = false;
            }
//            Log.i(TAG, "????:" + bufferPercentage);
        } else if (total>0&&Math.abs(total-current)<200) {
            Toast.makeText(getApplicationContext(),"?????",Toast.LENGTH_SHORT).show();
            nowTime.setText(stringForTime(0));
            progress.setProgress(0);
            superVideoView.stop();
            playOrPause.setImageResource(android.R.drawable.ic_media_play);
        }
    }

    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    private void setProgress(int current, int total) {
        if (progress != null) {
            if (total > 0) {
                // use long to avoid overflow
                long pos = 1000L * current / total;
                progress.setProgress((int) pos);
            }
            int percent = superVideoView.getBufferPercentage();
            progress.setSecondaryProgress(percent * 10);
        }

        if (totalTime != null)
            totalTime.setText(stringForTime(total));
        if (nowTime != null)
            nowTime.setText(stringForTime(current));
    }

    /**
     * ????
     */
    private void volumeChange(float deltaY) {
        if(viewControllerLight!=null){
            viewControllerLight.cancel();
        }

        int delta = (int) ((deltaY / screenHeight) * maxVolume);
        int volume;
        if (deltaY > 0) {
            volume = Math.min(initializeVoice + delta, maxVolume);
        } else {
            volume = Math.max(initializeVoice + delta, 0);
        }
        if (isDebug)
            Log.i(TAG, "??=" + volume + "," + delta + "," + (int) deltaY);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
        if (viewControllerVolume == null) {
            viewControllerVolume = new ViewController(getApplicationContext(), R.drawable.v_supreme_volume, 15);
        }
        if (0 == volume) {
            viewControllerVolume.setImage(R.drawable.v_supreme_volume_mute);
        } else if (0 == lastVolume) {
            viewControllerVolume.setImage(R.drawable.v_supreme_volume);
        }
        lastVolume = volume;
        viewControllerVolume.show(volume);
    }

    /**
     * ????
     */
    private void lightChange(float deltaY) {
        if(viewControllerVolume!=null){
            viewControllerVolume.cancel();
        }
        int delta = (int) (deltaY * 255 / screenHeight);
        int tLight = initializeLight + delta;
        tLight = tLight < 0 ? 0 : (tLight > 255 ? 255 : tLight);
        LightnessController.setLightness(this, tLight);
        if (isDebug)
            Log.i(TAG, "??=" + tLight + "," + delta + "," + (int) deltaY);
        if (viewControllerLight == null) {
            viewControllerLight = new ViewController(getApplicationContext(), R.drawable.v_supreme_brightness, 255);
        }
        viewControllerLight.show(tLight);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (isDebug)
            Log.i(TAG, "onProgressChanged-->" + progress + "," + fromUser);
        if (fromUser) {
            superVideoView.seekTo(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if (isDebug)
            Log.i(TAG, "onStartTrackingTouch-->" + seekBar);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (isDebug)
            Log.i(TAG, "onStartTrackingTouch-->" + seekBar);
    }

}




Java Source Code List

com.huilan.library_videoplay.AdvancedPlayerSimple.java
com.huilan.library_videoplay.AdvancedPlayer.java
com.huilan.library_videoplay.VideoViewPlay.java
com.huilan.library_videoplay.sample.LightnessController.java
com.huilan.library_videoplay.sample.MainActivity.java
com.huilan.library_videoplay.sample.TextActivity.java
com.huilan.library_videoplay.util.LightnessController.java
com.huilan.library_videoplay.util.ParseHtmlToUrl.java
com.huilan.library_videoplay.util.ViewController.java
com.huilan.library_videoplay.view.FullScreenVideoView.java
com.huilan.library_videoplay.view.SuperVideoView.java