This repository was archived by the owner on Aug 22, 2020. It is now read-only.
forked from JamesKyburz/youtube-audio-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·92 lines (74 loc) · 2.37 KB
/
index.js
File metadata and controls
executable file
·92 lines (74 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const ytdl = require('ytdl-core');
const FFmpeg = require('fluent-ffmpeg');
const { PassThrough } = require('stream');
const events = require('events');
const fs = require('fs');
const streamEmitter = new events.EventEmitter();
function streamify(uri, opt) {
const options = {
...opt,
quality: 'highestaudio',
audioFormat: 'mp3'
};
const streamPromise = ytdl
.getInfo(uri)
.then(info => {
const isLive = info.player_response.videoDetails.isLiveContent;
const streamSource = { isLive, info: {}, source: '' };
if (isLive) {
// source is the m3u8 url
streamSource.source = ytdl.chooseFormat(info.formats, {
quality: 'highestaudio'
}).url;
} else {
// source is the Readable stream
streamSource.source = ytdl.downloadFromInfo(info, options);
}
streamSource.isLive = isLive;
streamSource.info = info;
return streamSource;
})
.then(streamObj => {
const { isLive } = streamObj;
const { file, audioFormat, bitrate, startTime } = options;
const stream = file ? fs.createWriteStream(file) : new PassThrough();
const audioBitrate = bitrate || 128; // default bitrate is 128 if one was not passed
const ffmpeg = new FFmpeg(streamObj.source);
// Disable for undefined and livestreams
if (startTime && !isLive) {
ffmpeg.setStartTime(startTime);
}
// convert audio and start writing to stream
ffmpeg
.audioCodec('libmp3lame')
.audioBitrate(audioBitrate)
.format(audioFormat)
.pipe(stream);
// Error Emitters
// If it is NOT a livestream url, it has event listeners
if (!isLive) {
streamObj.source.on('error', error => {
streamEmitter.emit('error', error);
});
}
ffmpeg.on('error', error => {
if (!isLive) {
streamObj.source.end();
}
// If it is NOT a livestream url, it must be a readable stream
// which can be stopped when an error occurs
streamEmitter.emit('error', error);
});
// stream.source = streamObj;
stream.info = streamObj.info;
stream.ffmpeg = ffmpeg;
stream.isLive = isLive;
stream.emitter = streamEmitter;
return stream;
})
.catch(err => {
throw err;
});
return streamPromise;
}
module.exports = streamify;