實現播放視訊及彈幕

住你隔壁的文藝青年發表於2019-09-23

1:依賴: implementation ‘com.shuyu:GSYVideoPlayer:7.0.1’
implementation ‘com.github.ctiao:DanmakuFlameMaster:0.7.3’

2:佈局

<com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
    android:id="@+id/video_player"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:layout_centerInParent="true" />

<master.flame.danmaku.ui.widget.DanmakuView
    android:id="@+id/danmaku_view"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:layout_centerInParent="true" />

<LinearLayout
    android:layout_width="match_parent"
    android:id="@+id/line"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/butn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="傳送"></Button>

    <EditText

        android:id="@+id/ed"
        android:layout_width="324dp"
        android:layout_height="match_parent"></EditText>
</LinearLayout>
3:程式碼

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
OrientationUtils orientationUtils;
private DanmakuView danmaku_view;
private boolean showDanmaku;
private DanmakuContext danmakuContext;
/**
* 彈幕解析器
*/
private BaseDanmakuParser parser = new BaseDanmakuParser() {
@Override
protected IDanmakus parse() {
return new Danmakus();
}
};
private LinearLayout mOperationLayout;
private StandardGSYVideoPlayer video_player;
private Button butn1;
private EditText ed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
init();
initDanmaku();
}
private void init() {
video_player = (StandardGSYVideoPlayer) findViewById(R.id.video_player);
String source1 = “http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4”;
video_player.setUp(source1, true, “測試視訊”);
AudioManager service = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (service != null) {
service.setRingerMode(AudioManager.RINGER_MODE_SILENT);
service.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);
}
//增加封面
ImageView imageView = new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.ic_launcher);
video_player.setThumbImageView(imageView);
//增加title
video_player.getTitleTextView().setVisibility(View.VISIBLE);
//設定返回鍵
video_player.getBackButton().setVisibility(View.VISIBLE);
//設定旋轉
orientationUtils = new OrientationUtils(this, video_player);
//設定全屏按鍵功能,這是使用的是選擇螢幕,而不是全屏
video_player.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
orientationUtils.resolveByClick();
}
});
//是否可以滑動調整
video_player.setIsTouchWiget(true);
//設定返回按鍵功能
video_player.getBackButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
video_player.startPlayLogic();
}
@Override
protected void onPause() {
super.onPause();
video_player.onVideoPause();
if (danmaku_view != null && danmaku_view.isPrepared()) {
danmaku_view.pause();
}

}
@Override
protected void onResume() {
    super.onResume();
    video_player.onVideoResume();
    if (danmaku_view != null && danmaku_view.isPrepared() && danmaku_view.isPaused()) {
        danmaku_view.resume();
    }

}
@Override
protected void onDestroy() {
    super.onDestroy();
    GSYVideoManager.releaseAllVideos();
    if (orientationUtils != null)
        orientationUtils.releaseListener();
    showDanmaku = false;
    if (danmaku_view != null) {
        danmaku_view.release();
        danmaku_view = null;
    }
}
@Override
public void onBackPressed() {
    //先返回正常狀態
    if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        video_player.getFullscreenButton().performClick();
        return;
    }
    //釋放所有
    video_player.setVideoAllCallBack(null);
    super.onBackPressed();
}
private void initView() {
    danmaku_view = (DanmakuView) findViewById(R.id.danmaku_view);
    video_player = (StandardGSYVideoPlayer) findViewById(R.id.video_player);
    butn1 = (Button) findViewById(R.id.butn1);
    mOperationLayout = (LinearLayout) findViewById(R.id.line);
    butn1.setOnClickListener(this);
    ed = (EditText) findViewById(R.id.ed);
    //監聽由於輸入法彈出所致的沉浸問題
    getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
        @Override
        public void onSystemUiVisibilityChange(int visibility) {
            if (visibility == View.SYSTEM_UI_FLAG_VISIBLE) {
                onWindowFocusChanged(true);
            }
        }
    });
}
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.butn1:
            String data = ed.getText().toString();
            if (!TextUtils.isEmpty(data)) {
                addDanmaku(data, true);
                ed.setText("");
            }
            break;
    }
}
/**
 * sp轉px的方法。
 */
public int sp2px(float spValue) {
    final float fontScale = getResources().getDisplayMetrics().scaledDensity;
    return (int) (spValue * fontScale + 0.5f);
}
private void addDanmaku(String data, boolean b) {

//彈幕例項BaseDanmaku,傳入引數是彈幕方向
BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
danmaku.text = data;
danmaku.padding = 5;
danmaku.textSize = sp2px(20);
danmaku.textColor = Color.WHITE;
danmaku.setTime(danmaku_view.getCurrentTime());
//加邊框
if (b) {
danmaku.borderColor = Color.GREEN;
}
danmaku_view.addDanmaku(danmaku);
}
/**
* 初始化彈幕元件
*/
private void initDanmaku() {
//給彈幕檢視設定回撥,在準備階段獲取彈幕資訊並開始
danmaku_view.setCallback(new DrawHandler.Callback() {
@Override
public void prepared() {
showDanmaku = true;
danmaku_view.start();
generateSomeDanmaku();
}

        @Override
        public void updateTimer(DanmakuTimer timer) {

        }

        @Override
        public void danmakuShown(BaseDanmaku danmaku) {

        }

        @Override
        public void drawingFinished() {

        }
    });
    //快取,提升繪製效率
    danmaku_view.enableDanmakuDrawingCache(true);
    //DanmakuContext主要用於彈幕樣式的設定
    danmakuContext = DanmakuContext.create();
    danmakuContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3);//描邊
    danmakuContext.setDuplicateMergingEnabled(true);//重複合併
    danmakuContext.setScrollSpeedFactor(1.2f);//彈幕滾動速度
    //讓彈幕進入準備狀態,傳入彈幕解析器和樣式設定
    danmaku_view.prepare(parser, danmakuContext);

}

private void generateSomeDanmaku() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (showDanmaku) {
                int time = new Random().nextInt(300);
                String content = "" + time + time;
                addDanmaku(content, false);
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus && Build.VERSION.SDK_INT >= 19) {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}

}

相關文章