Android彈幕架構 黑暗火焰使

來源:互聯網
上載者:User

標籤:

笑談風雲,一語定乾坤。大家好,我是皖江。

今天我將分享由BiliBili開源的Android彈幕架構(DanmakuFlameMaster)的學習經驗。

我是將整個架構以model的形式引入項目中的,這樣更方便的觀察源碼。也可以通過依賴的方式注入進來

dependencies {    compile 'com.github.ctiao:DanmakuFlameMaster:0.5.3'}

先放一下我要做成的:


頁面分析

從來看,整個UI分成了三層。最下面是視頻層,中間是彈幕層,頂層是控制層。現在市場上主流的ApsaraVideo for Live軟體大多都是這樣分層的,不同的是直播類的話,可能還會再多一層互動層,顯示簽到資訊、礼物資訊什麼的。

既然是分層的話,我就直接用FrameLayout幀布局來實現了。貼一下我的布局檔案:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <VideoView        android:id="@+id/vv_video"        android:layout_width="match_parent"        android:layout_height="match_parent" />    <master.flame.danmaku.ui.widget.DanmakuView        android:id="@+id/sv_danmaku"        android:layout_width="match_parent"        android:layout_height="match_parent" />    <include android:id="@+id/media_controller"        android:layout_width="match_parent"        android:layout_height="fill_parent"        layout="@layout/media_controller" /></FrameLayout>
控制層的布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <LinearLayout        android:gravity="center_vertical"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_gravity="bottom"        android:background="#8acc22dd" >        <Button            android:layout_weight="1"            android:id="@+id/rotate"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:text="@string/rotate" />        <Button            android:layout_width="0dp"            android:layout_weight="1"            android:id="@+id/btn_hide"            android:layout_height="wrap_content"            android:text="@string/hide_danmaku" />        <Button            android:id="@+id/btn_show"            android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="@string/show_danmaku" />        <Button            android:id="@+id/btn_pause"            android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="@string/pause_danmaku" />        <Button            android:id="@+id/btn_resume"            android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="@string/resume_danmaku" />        <Button            android:id="@+id/btn_send"            android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="@string/send_danmaku" />        <Button            android:id="@+id/btn_send_image_text"            android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="@string/send_danmaku_image_text" />                <Button            android:id="@+id/btn_send_danmakus"            android:layout_width="0dp"            android:layout_weight="1"            android:layout_height="wrap_content"            android:text="@string/send_danmakus" />    </LinearLayout></FrameLayout>

寫完布局,先寫一個初始化的方法:

        //設定最大行數        HashMap<Integer,Integer> maxLinesPair = new HashMap<>();        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL,5);//滾動彈幕最大顯示5行        //設定是否禁止重疊        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<>();        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, true);        overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_TOP, true);        mDanmakuContext = DanmakuContext.create();//初始化上下文        mDanmakuContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN,3);//設定彈幕類型        mDanmakuContext.setDuplicateMergingEnabled(false);//設定是否合并重複彈幕        mDanmakuContext.setScrollSpeedFactor(1.2f);//設定彈幕捲動速度        mDanmakuContext.setScaleTextSize(1.2f);//設定彈幕字型大小        mDanmakuContext.setCacheStuffer(new SpannedCacheStuffer(),mCacheStufferAdapter);//設定緩衝繪製填充器 圖文混排使用SpannedCacheStuffer          mDanmakuContext.setMaximumLines(maxLinesPair);//設定最大行數        mDanmakuContext.preventOverlapping(overlappingEnablePair); //設定是否禁止重疊        mParser = createParser(this.getResources().openRawResource(R.raw.comments));//載入彈幕資源檔        mDvDanmaku.prepare(mParser, mDanmakuContext);        mDvDanmaku.showFPS(true);        mDvDanmaku.enableDanmakuDrawingCache(true);


再貼一下繪製填充器的實現,主要實現了將圖片和文字流向在一起的效果

    private SpannableStringBuilder createSpannable(Drawable drawable) {        String text = "bitmap";        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);        ImageSpan span = new ImageSpan(drawable);        spannableStringBuilder.setSpan(span, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);        spannableStringBuilder.append("圖文混排");        spannableStringBuilder.setSpan(new BackgroundColorSpan(Color.parseColor("#8A2233B1")), 0, spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);        return spannableStringBuilder;    }

在BaseDanmaku這個類下,定義了彈幕的基本運動形式:TYPE_SCROLL_RL、TYPE_SCROLL_LR、TYPE_FIX_TOP、TYPE_FIX_BOTTOM和TYPE_SPECIAL。也就是從右入左出、左入右出(逆向彈幕)、頂部彈幕、底部彈幕以及進階彈幕。(除此之外還有指令碼彈幕)

在初始化的時候,需要傳入一個特有的彈幕上下文DanmukuContext,通過上下文來初始化一些設定。彈幕資源是儲存在xml檔案下的,大致格式如下:

.

<i>    <chatserver>chat.bilibili.com</chatserver>    <chatid>2962351</chatid>    <mission>0</mission>    <maxlimit>1500</maxlimit>    <source>k-v</source>    <d p="145.91299438477,1,25,16777215,1422201001,0,D6673695,757075520">我從未見過如此厚顏無恥之人</d></i>
頭資訊不需要太多關注,來看看d標籤下p對應參數的具體意義:

第一個:彈幕出現的時間

第二個:彈幕類型(1、從右至左;6、從左至右;5、頂部彈幕;4、底部彈幕;7、進階彈幕;8、指令碼彈幕’)

第三個:字型大小

第四個:顏色

第五個:時間戳記

第六個:彈幕池ID

第七個:使用者hash值

第八個:彈幕id

以下是彈幕具體解析代碼


    /**     * 從彈幕檔案中提起彈幕     * @param stream     * @return     */    private BaseDanmakuParser createParser(InputStream stream) {        if (stream == null) {            return new BaseDanmakuParser() {                @Override                protected Danmakus parse() {                    return new Danmakus();                }            };        }        ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);//建立一個BiliDanmakuLoader執行個體來載入彈幕流檔案        try {            loader.load(stream);        } catch (IllegalDataException e) {            e.printStackTrace();        }        BaseDanmakuParser parser = new BiliDanmukuParser();//彈幕解析者        IDataSource<?> dataSource = loader.getDataSource();        parser.load(dataSource);        return parser;    }

具體解析方案:

            String tagName = localName.length() != 0 ? localName : qName;            tagName = tagName.toLowerCase(Locale.getDefault()).trim();            if (tagName.equals("d")) {                String pValue = attributes.getValue("p");                // parse p value to danmaku                String[] values = pValue.split(",");                if (values.length > 0) {                    long time = (long) (Float.parseFloat(values[0]) * 1000); // 出現時間                    int type = Integer.parseInt(values[1]); // 彈幕類型                    float textSize = Float.parseFloat(values[2]); // 字型大小                    int color = Integer.parseInt(values[3]) | 0xFF000000; // 顏色                    item = mContext.mDanmakuFactory.createDanmaku(type, mContext);                    if (item != null) {                        item.setTime(time);                        item.textSize = textSize * (mDispDensity - 0.6f);                        item.textColor = color;                        item.textShadowColor = color <= Color.BLACK ? Color.WHITE : Color.BLACK;                    }                }            }
彈幕資源載入完畢後,就調用mDvDanmuku的prepare()方法,執行準備。當準備完畢的時候,就會調用DrawHandler.CallBack()回調中的prepared方法。然後在這個prepared方法中正式讓彈幕啟動。調用順序如下:

mDvDanmaku.prepare(mParser, mDanmakuContext);//傳入解析完成的彈幕和上下文

然後執行DanmukuView下的prepare()方法

    private void prepare() {        if (handler == null)            handler = new DrawHandler(getLooper(mDrawingThreadType), this, mDanmakuVisible);//建立一個Handler    }
通過這個Handler來實現進程間的通訊

        handler.setConfig(config);        handler.setParser(parser);        handler.setCallback(mCallback);        handler.prepare();-》會讓handler發送一個message  去執行正真的準備
DrawHandler中有一個回調
    public interface Callback {        public void prepared();        public void updateTimer(DanmakuTimer timer);        public void danmakuShown(BaseDanmaku danmaku);        public void drawingFinished();    }
真正的準備

mTimeBase = SystemClock.uptimeMillis();                if (mParser == null || !mDanmakuView.isViewReady()) {//沒有準備好,延時0.1秒後再執行                    sendEmptyMessageDelayed(PREPARE, 100);                } else {                    prepare(new Runnable() {                        @Override                        public void run() {                            pausedPosition = 0;                            mReady = true;                            if (mCallback != null) {                                mCallback.prepared();                            }                        }                    });                }
以上是彈幕View的啟動調用流程。
那麼,怎麼添加彈幕捏?元芳,你怎麼看?(TM我怎麼知道我怎麼看)看下面
    private void addDanmaku(boolean islive) {        BaseDanmaku danmaku = mDanmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);//添加一條從右至左的滾動彈幕        if (danmaku == null || mDvDanmaku == null) {            return;        }        danmaku.text = "這是一條彈幕" + System.nanoTime();        danmaku.padding = 5;        danmaku.priority = 0;  // 可能會被各種過濾器過濾並隱藏顯示  設定為1的話,就一定會顯示  適用於本機發送的彈幕        danmaku.isLive = islive;        danmaku.setTime(mDvDanmaku.getCurrentTime() + 1200);        danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f);        danmaku.textColor = Color.RED;//預設設定為紅色字型        danmaku.textShadowColor = Color.WHITE;        danmaku.borderColor = Color.GREEN;//為了區別其他彈幕與自己發的彈幕,再給自己發的彈幕加上邊框        mDvDanmaku.addDanmaku(danmaku);    }

以上,就是黑暗火焰使基本使用方法。

Android彈幕架構 黑暗火焰使

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.