获取Bilibili直播流

Introduction

说到获取直播流,就不得不提到浏览器自带的开发者工具。啥都能看到,文体两开花,弘扬……

但是这总有些麻烦,另外,如果使用低性能平台,在bilibili直播这样的大型页面打开开发者工具,真的会影响心情。

更优雅的方式应该是——

Code

/**
 * Get Bilibili live play url
 * @param {number}   roomId      Room's id, short or long
 * @param {number}   lineNumber  Server line [ 0(main) | 1 ~ 3(bak) ]
 * @param {number}   quality     Video's quality [ 1(lowest) ~ 4(highest) ]
 * @param {string}   platform    Type of url [ h5(m3u8) | web(flv) ]
 */
async function getBiliLiveUrl(
    roomId = 3,
    lineNumber = 0,
    quality = 4,
    platform = 'web'
) {
    let https = require('https');
    let readline = require('readline');

    let biliApi = {
        roomInit: 'api.live.bilibili.com/room/v1/Room/room_init',
        playUrl: 'api.live.bilibili.com/room/v1/Room/playUrl'
    };
    let roomInfo = await fetchJsonAsync(
        biliApi.roomInit
        + `?id=${roomId}`
    );
    if (roomInfo.data.live_status == '1') {
        let playInfo = await fetchJsonAsync(
            biliApi.playUrl
            + `?cid=${roomInfo.data.room_id}`
            + `&quality=${quality}`
            + `&platform=${platform}`
        );
        return playInfo.data.durl[lineNumber].url;
    } else {
        return null;
    }

    async function fetchJsonAsync(url) {
        return new Promise(resolve => {
            https.get('https://' + url, res => {
                let rawData = '';
                res.on('data', chunk => rawData += chunk);
                res.on('end', () => resolve(JSON.parse(rawData)));
            });
        });
    }
}