Skip to content
This repository has been archived by the owner on Sep 30, 2020. It is now read-only.

Commit

Permalink
Alter YouTube music handler to get an audio-only Opus format, to incr…
Browse files Browse the repository at this point in the history
…ease speed of caching
  • Loading branch information
Ovyerus committed Jan 11, 2018
1 parent 0ca0481 commit 2f37728
Showing 1 changed file with 20 additions and 28 deletions.
48 changes: 20 additions & 28 deletions src/cmd/main/music/handlers/YouTubeHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,32 @@
const ytdl = require('ytdl-core');
const got = require('got');

const ITAG = '251'; // Preferred iTag quality to get. Default: 251.

class YouTubeHandler {
constructor() {}

getInfo(url) {
return new Promise((resolve, reject) => {
if (typeof url !== 'string') throw new TypeError('url is not a string.');

ytdl.getInfo(url, {filter: 'audioonly'}).then(info => {
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};

return res;
}).then(resolve).catch(reject);
});
async getInfo(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');

let info = await ytdl.getInfo(url);
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};

return res;
}

getStream(url) {
return new Promise((resolve, reject) => {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
async getStream(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');

ytdl.getInfo(url, {filter: 'audioonly'}).then(info => {
// Sort the various bitrates and pick the highest quality (that is 96kbps or less)
let bitrates = info.formats.filter(f => f.audioBitrate <= 96 && typeof f.audioBitrate === 'number');
bitrates = bitrates.map(f => {return {bitrate: f.bitrate, url: f.url};}).sort((a, b) => b.bitrate - a.bitrate);

return got.stream(bitrates[0].url);
}).then(resolve).catch(reject);
});
let info = await ytdl.getInfo(url)
return got.stream(info.formats.find(f => f.itag === ITAG).url);
}
}

Expand Down

0 comments on commit 2f37728

Please sign in to comment.