關於Video標籤直播的思考

關於Video標籤直播的思考

背景

  前提:在公司直播H5SDK應用中要求直播過程當中不能夠暫停直播。某天用戶反饋了幾個bug,第一:說經過耳機聽課能夠暫停直播(公司不容許直播過程當中暫停),第二:說在回放的時候經過耳機暫停播放時UI並無發生變化,仍是播放狀態(當前鬥魚也存在這個問題),第三:在safari瀏覽器中會出現直播倒退的狀況。jquery

解決方案

  解決第一個問題,經過耳機聽課能夠暫停直播:經過監聽video標籤的pause事件,當發生回調時候就再次調用play方法,代碼以下:linux

var ele = document.querySelector('video');
// 當用戶經過耳機暫停時,調用play方法
ele.addEventListenr('pause', function() {
    ele.play();
});
複製代碼

  解決第二個問題,回放過程當中經過耳機暫停播放時UI並無發生改變:經過監聽video標籤pause事件,當發生回調的時候同時調用一下SDK暴露出來的接口改變UI(這樣弊端會調用兩次pause()方法)。代碼以下:android

var ele = document.querySelector('video');
var sdk = new H5SDK();
ele.addEventListener('pause', function() {
    // sdk內部暴露給外部調用的方法,調用該事件UI變爲暫停
    sdk.stop();
});
ele.addEventListener('play', function() {
    // sdk內部暴露給外部調用的方法,調用該事件UI發變爲播放
    sdk.resume();
})
複製代碼

  解決第三個問題,首先分析爲何只有在safari中直播會出現倒退狀況。通過分析發現直播過程當中若是流斷了(網絡斷開或者服務端推流斷了)safari瀏覽器內核會本身觸發一個addEventListenr('pause')回調,致使咱們在修改第一個bug的時候寫的ele.play()執行了。那麼爲何會倒退呢?safari中直播流斷了它認爲這是一個完整回放文件而後一個完整回放文件播放到最後的時候在調用ele.play()函數時就重頭播放了,因此產生了直播倒退。那麼爲何只有safari中會有這種狀況呢?由於chrome等瀏覽器直播流斷開後不會觸發addEventListenr('pause')回調,天然不會有問題。那麼要從根本解決這個問題就要區分出來是用戶主動觸發暫停事件(主動暫停)仍是因爲用戶網絡或者服務端推流致使buffer不足(被動暫停)致使addEventListenr('pause')回調。web

主動暫停與被動暫停

  咱們須要寫一個通用的工具類,該工具類對外提供video暫停時候是用戶主動觸發的仍是buffer不足致使的。
  該類須要注意第一點:兼容性,兼容safari以及其餘瀏覽器。第二點:功能完善性,提供暫停時不一樣的事件類型(用戶觸發仍是buffer不足)
  基本思路:對於safari瀏覽器在buffer不足的時候老是返回-0.001xxxxx,能夠粗略的理解當小於0.001的時候就是buffer不足狀況。因此咱們監聽pause回調只要buffer<0.001就認爲是buffer不足,其餘狀況就認爲是用戶主動觸發。對於其餘瀏覽器,咱們經過開啓定時器按期檢查Video的state(這個api在safari一直返回狀態是4),來肯定buffer是否爲空。 封裝代碼以下:
VideoHelp.tschrome

import Browser from './browser';

const Safari_Min_Buffer = 0.001;
const rState = {
  HAVE_NOTHING: 0,
  HAVE_METADATA: 1,
  HAVE_CURRENT_DATA: 2,
  HAVE_FUTURE_DATA: 3,
  HAVE_ENOUGH_DATA: 4,
};
const Pause_Type = {
  Self: '1', // 主動暫停
  Other: '2', // 網絡等因素致使暫停
}

const getBufferLength = (videoMedia) => {
  const me = videoMedia;
  if (!me || !me.buffered || me.buffered.length === 0) {
    return 0;
  }
  const len = me.buffered.length;
  const currentTime = me.currentTime;
  const lastBufferedEnd = me.buffered.end(len - 1);
  // console.log((lastBufferedEnd - currentTime)); -0.0012346326666663465
  return parseFloat((lastBufferedEnd - currentTime).toFixed(3)); // -0.001
};

class VideoHelp {
  private ele: HTMLVideoElement | HTMLAudioElement;
  private pauseCb: Function;
  private bufferEmpty: boolean = false;

  constructor(ele: HTMLVideoElement, pauseCb: Function) {
    this.ele = ele;
    this.pauseCb = pauseCb;
    this.ele.addEventListener('pause', this.handleVideoPause.bind(this));
    this.ele.addEventListener('canplay', this.handleCanplay.bind(this));
    this.checkBufferEmpty();
  }

  private handleCanplay() {
    this.bufferEmpty = false;
  }

  private checkBufferEmpty() {
    if (!this.bufferEmpty && (this.ele.readyState <= rState.HAVE_CURRENT_DATA)) {
      this.bufferEmpty = true;
      this.pauseCb(Pause_Type.Other);
    }
    setTimeout(this.checkBufferEmpty.bind(this), 50);
  }

  private handleVideoPause() {
    if (Browser.safari) {
      const buffer = getBufferLength(this.ele);
      console.log(buffer);
      buffer <= Safari_Min_Buffer ? this.pauseCb(Pause_Type.Other) : this.pauseCb(Pause_Type.Self);
    } else {
      this.pauseCb(Pause_Type.Self);
    }
  }
}

export default VideoHelp;

複製代碼

外部調用過程express

import VideoHelp from './video-help.ts'

const ele = document.getElementById('video');
const vh = new VideoHelp(ele, function(type) {
    // type爲1時候是主動暫停
    // type爲2時候是buffer不足暫停
    console.log(type);
});
複製代碼

摘自flv.js的瀏覽器判斷類apache

/*
 * Copyright (C) 2016 Bilibili. All Rights Reserved.
 *
 * @author zheng qian <xqq@xqq.im>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable */
let Browser = {};

function detect() {
    // modified from jquery-browser-plugin

    let ua = self.navigator.userAgent.toLowerCase();

    let match = /(edge)\/([\w.]+)/.exec(ua) ||
        /(opr)[\/]([\w.]+)/.exec(ua) ||
        /(chrome)[ \/]([\w.]+)/.exec(ua) ||
        /(iemobile)[\/]([\w.]+)/.exec(ua) ||
        /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) ||
        /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) ||
        /(webkit)[ \/]([\w.]+)/.exec(ua) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
        /(msie) ([\w.]+)/.exec(ua) ||
        ua.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(ua) ||
        ua.indexOf('compatible') < 0 && /(firefox)[ \/]([\w.]+)/.exec(ua) ||
        [];

    let platform_match = /(ipad)/.exec(ua) ||
        /(ipod)/.exec(ua) ||
        /(windows phone)/.exec(ua) ||
        /(iphone)/.exec(ua) ||
        /(kindle)/.exec(ua) ||
        /(android)/.exec(ua) ||
        /(windows)/.exec(ua) ||
        /(mac)/.exec(ua) ||
        /(linux)/.exec(ua) ||
        /(cros)/.exec(ua) ||
        [];

    let matched = {
        browser: match[5] || match[3] || match[1] || '',
        version: match[2] || match[4] || '0',
        majorVersion: match[4] || match[2] || '0',
        platform: platform_match[0] || ''
    };

    let browser = {};
    if (matched.browser) {
        browser[matched.browser] = true;

        let versionArray = matched.majorVersion.split('.');
        browser.version = {
            major: parseInt(matched.majorVersion, 10),
            string: matched.version
        };
        if (versionArray.length > 1) {
            browser.version.minor = parseInt(versionArray[1], 10);
        }
        if (versionArray.length > 2) {
            browser.version.build = parseInt(versionArray[2], 10);
        }
    }

    if (matched.platform) {
        browser[matched.platform] = true;
    }

    if (browser.chrome || browser.opr || browser.safari) {
        browser.webkit = true;
    }

    // MSIE. IE11 has 'rv' identifer
    if (browser.rv || browser.iemobile) {
        if (browser.rv) {
            delete browser.rv;
        }
        let msie = 'msie';
        matched.browser = msie;
        browser[msie] = true;
    }

    // Microsoft Edge
    if (browser.edge) {
        delete browser.edge;
        let msedge = 'msedge';
        matched.browser = msedge;
        browser[msedge] = true;
    }

    // Opera 15+
    if (browser.opr) {
        let opera = 'opera';
        matched.browser = opera;
        browser[opera] = true;
    }

    // Stock android browsers are marked as Safari
    if (browser.safari && browser.android) {
        let android = 'android';
        matched.browser = android;
        browser[android] = true;
    }

    browser.name = matched.browser;
    browser.platform = matched.platform;

    for (let key in Browser) {
        if (Browser.hasOwnProperty(key)) {
            delete Browser[key];
        }
    }
    Object.assign(Browser, browser);
}

detect();

export default Browser;
複製代碼

總結

  1. 分析了若是在直播過程當中不容許用戶暫停問題
  2. 分析了用戶經過耳機控制暫停播放事件時同步給UI解決方案
  3. 提供了區分用戶主動暫停和被動暫停解決問題思路
相關文章
相關標籤/搜索