Code Monkey home page Code Monkey logo

discord-ytdl-core's Introduction

discord-ytdl-core

Simple ytdl wrapper for discord bots with custom ffmpeg args support.

Installing

First of all, you need to install ytdl-core with npm install --save ytdl-core.

Install ytdl core

$ npm i ytdl-core

Install discord ytdl core

$ npm i discord-ytdl-core

https://www.npmjs.com/package/discord-ytdl-core

Opus [optional]

Please install opus engine if you want to encode the stream to opus format.

Supported Opus Engines

API

YTDL(youtubeURL, options)

Similar to ytdl-core but this method allows you to pass custom FFmpeg args in options.

ytdl("https://www.youtube.com/watch?v=QnL5P0tFkwM", {
    filter: "audioonly",
    fmt: "mp3",
    encoderArgs: ['-af', 'bass=g=10']
}).pipe(fs.createWritestream("bass_boosted.mp3"));

YTDL.arbitraryStream(source, options)

This method allows you to play the stream from other sources rather than just youtube. Stream source must be a string or stream object (internal.Readable | internal.Duplex). Through URL: https://listen.moe/kpop/opus

Using fs:

let stream = fs.createReadStream("./music.mp4");
ytdl.arbitraryStream(stream, {
    fmt: "mp3",
    encoderArgs: ["bass=g=5"]
}).pipe(fs.createWriteStream("./music.mp3"))

Options

This package provides 4 extra options excluding ytdl-core options.

  • seek: This option takes the time in seconds. If this option is provided, it will return the stream from that frame. Seek option is provided here because discord.js seek doesn't work for ogg/opus & webm/opus stream. This option is ignored when the supplied parameter type isn't a number.

  • encoderArgs: This option takes the Array of FFmpeg arguments. Invalid args will throw error and crash the process. This option is ignored when the supplied parameter type isn't array. Invalid FFmpeg args might crash the process.

  • opusEncoded: This option takes a Boolean value. If true, it returns opus encoded stream. If fmt option isn't provided, it returns converted stream type of discord.js. Other values returns unknown stream if opusEncoded is false.

  • fmt: Forcefully changes the stream format. Don't use this option for default value. Even though this option changes the format, it returns opus stream if opusEncoded is set to true.

  • Other options are the options for ytdl-core.

Example

Playing Opus Encoded Stream

const { ytdl } = require("discord-ytdl-core");
const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
    console.log("ready")
});

client.on("message", msg => {
    if (msg.author.bot || !msg.guild) return;
    if (msg.content === "!play") {
        if (!msg.member.voice.channel) return msg.channel.send("You're not in a voice channel?");
        let stream = ytdl("https://www.youtube.com/watch?v=QnL5P0tFkwM", {
            filter: "audioonly",
            opusEncoded: true,
            encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200']
        });
        
        msg.member.voice.channel.join()
        .then(connection => {
            let dispatcher = connection.play(stream, {
                type: "opus"
            })
            .on("finish", () => {
                msg.guild.me.voice.channel.leave();
            })
        });
    }
});

client.login("TOKEN");

Unknown Stream

const { ytdl } = require("discord-ytdl-core");
const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
    console.log("ready")
});

client.on("message", msg => {
    if (msg.author.bot || !msg.guild) return;
    if (msg.content === "!play") {
        if (!msg.member.voice.channel) return msg.channel.send("You're not in a voice channel?");
        let stream = ytdl("https://www.youtube.com/watch?v=QnL5P0tFkwM", {
            filter: "audioonly",
            opusEncoded: false,
            fmt: "mp3",
            encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200']
        });
        
        msg.member.voice.channel.join()
        .then(connection => {
            let dispatcher = connection.play(stream, {
                type: "unknown"
            })
            .on("finish", () => {
                msg.guild.me.voice.channel.leave();
            })
        });
    }
});

client.login("TOKEN");

Converted Stream

const { ytdl } = require("discord-ytdl-core");
const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
    console.log("ready")
});

client.on("message", msg => {
    if (msg.author.bot || !msg.guild) return;
    if (msg.content === "!play") {
        if (!msg.member.voice.channel) return msg.channel.send("You're not in a voice channel?");
        let stream = ytdl("https://www.youtube.com/watch?v=QnL5P0tFkwM", {
            filter: "audioonly",
            opusEncoded: false,
            encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200']
        });
        
        msg.member.voice.channel.join()
        .then(connection => {
            let dispatcher = connection.play(stream, {
                type: "converted"
            })
            .on("finish", () => {
                msg.guild.me.voice.channel.leave();
            })
        });
    }
});

client.login("TOKEN");

Downloading the video

const { ytdl } = require("discord-ytdl-core");
const { createWriteStream } = require ("fs");

const url = "https://www.youtube.com/watch?v=QnL5P0tFkwM";

let stream = ytdl(url, {
    encoderArgs: ["-af", "asetrate=44100*1.25,bass=g=20,dynaudnorm=f=150"],
    fmt: "mp3",
    opusEncoded: false
});

stream.pipe(createWriteStream(__dirname+"/test.mp3"));

Arbitrary Stream

const { ytdl } = require("discord-ytdl-core");
const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
    console.log("ready")
});

client.on("message", msg => {
    if (msg.author.bot || !msg.guild) return;
    if (msg.content === "!play") {
        if (!msg.member.voice.channel) return msg.channel.send("You're not in a voice channel?");
        let stream = ytdl.arbitraryStream("https://listen.moe/kpop/opus", {
            opusEncoded: true,
            encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200']
        });
        
        msg.member.voice.channel.join()
        .then(connection => {
            let dispatcher = connection.play(stream, {
                type: "opus"
            })
            .on("finish", () => {
                msg.guild.me.voice.channel.leave();
            })
        });
    }
});

client.login("TOKEN");

Other functions

Check out ytdl-core for other functions.

Sponsor this project

Related

discord-ytdl-core's People

Contributors

ehsanfox avatar jamesdools avatar twlite avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

discord-ytdl-core's Issues

Sometimes i have an error

Status code: 416 Error [ERR_UNHANDLED_ERROR]: Unhandled error. (undefined) at PassThrough.emit (events.js:299:17) at errorOrDestroy (internal/streams/destroy.js:108:12) at PassThrough.onerror (_stream_readable.js:729:7) at PassThrough.emit (events.js:310:20) at PassThrough.<anonymous> (E:\KrzysBot\node_modules\ytdl-core\lib\index.js:139:16) at PassThrough.emit (events.js:310:20) at ClientRequest.<anonymous> (E:\KrzysBot\node_modules\miniget\dist\index.js:163:28) at Object.onceWrapper (events.js:417:26) at ClientRequest.emit (events.js:310:20) at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:596:27) { code: 'ERR_UNHANDLED_ERROR', context: undefined }
i add try cause bot go down
`stream.destroy = () => {
stream._isDestroyed = true;
if (req.abort) req.abort();
req.end();
req.removeListener('data', ondata);
req.unpipe();
};

// Forward events from the request to the stream.
[
'abort', 'request', 'response', 'error', 'retry', 'reconnect',
].forEach(event => {
req.prependListener(event, arg => {

  try {
    stream.emit(event, arg);
  } catch (error) {
    console.error(error)
  }


  
});

});

req.pipe(stream);
};`

MinigetError: input stream: Status code: 403

MinigetError: input stream: Status code: 403
at ClientRequest. (/home/container/node_modules/miniget/dist/index.js:211:27)
at Object.onceWrapper (events.js:483:26)
at ClientRequest.emit (events.js:376:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:647:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
at TLSSocket.socketOnData (_http_client.js:515:22)
at TLSSocket.emit (events.js:376:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at TLSSocket.Readable.push (internal/streams/readable.js:223:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:188:23) {
statusCode: 403
}

This error come when playing a long playlist . Some people on ydl guild support server said that it can be a little rate limit. Anyone have found a real fix?

Problem with seek option

Hi,

I'm trying to make a seek command using this package, now when I originally play the song I do it like this:

// This plays the audio
        serverQueue.connection.play(await stream, {type: 'opus', bitrate: 'auto', seek: 0})
            // if the song ends
            .on('finish', reason => {
                if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.');
                else console.error("line 49 music controller, log: " + reason);
              
                serverQueue.songs.shift();
                // play the first song in the array
                this.startPlay(serverQueue.songs[0], message);
            })
            .on('error', error => {
                console.error("Lib/MusicController.js:" + error);
                message.channel.send(embeds.error(message.author, `\`${error}\``))
                queue.delete(message.guild.id);
                return;
            })
            .on('begin', error => console.error("MusicController.js Begin Error:" + error));
        // Set the default volume
        serverQueue.connection.dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
        serverQueue.textChannel.send(embeds.extended(message.author, `**Play**`, `๐ŸŽถ Started playing: **${song.title}**`, `https://img.youtube.com/vi/${song.id}/mqdefault.jpg`));

When seeking I do the following:

async seek(message, timeStamp) {
        serverQueue = queue.get(message.guild.id);

        serverQueue.connection.play(serverQueue.currentSong, {type: 'opus', bitrate: 'auto', seek: timeStamp})
    }

Now when I run the seek function, I can hear that the dispatcher goes a little bit into the song, but shortly dies after. How come I resolve this issue?

Regards Fred

Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed

Hi, I just want to run

const ytdl = require('discord-ytdl-core');
...
const dispatcher = serverQueue.connection
    .play(ytdl(song.url, {
      filter: 'audioonly',
      opusEncoded: true,
      encoderArgs: ['-af', queue.filters],
    }))
...

but it throws

events.js:292
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
    at doWrite (_stream_writable.js:399:19)
    at writeOrBuffer (_stream_writable.js:387:5)
    at Socket.Writable.write (_stream_writable.js:318:11)
    at PassThrough.ondata (_stream_readable.js:716:22)
    at PassThrough.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:271:9)
    at PassThrough.Readable.push (_stream_readable.js:212:10)
    at PassThrough.Transform.push (_stream_transform.js:152:32)
    at PassThrough.afterTransform (_stream_transform.js:96:10)
Emitted 'error' event on FFmpeg instance at:
    at errorOrDestroy (internal/streams/destroy.js:108:12)
    at FFmpeg.onerror (_stream_readable.js:752:7)
    at FFmpeg.emit (events.js:315:20)
    at Socket.processError (F:\projects\discord\bot\musicbot\node_modules\prism-media\src\core\FFmpeg.js:64:40)
    at Socket.emit (events.js:315:20)
    at errorOrDestroy (internal/streams/destroy.js:108:12)
    at onwriteError (_stream_writable.js:418:5)
    at onwrite (_stream_writable.js:445:5)
    at doWrite (_stream_writable.js:399:11)
    at writeOrBuffer (_stream_writable.js:387:5) {
  code: 'ERR_STREAM_DESTROYED'
}

Version

Windows 10 64 bits
ffmpeg v3.4
node v12.18.4
"@discordjs/opus": "^0.3.3",
"discord-ytdl-core": "^5.0.0",
"discord.js": "^12.4.1",

Tests

tested song
tested mix
(same error)

Thank you in advance

error write EPIPE

can anybody tell me why this is returning the Write EPIPE error ?

const ytdl = require('discord-ytdl-core')
stream = ytdl('https://www.youtube.com/watch?v=CqsgCsU8SOA',{
headers: {
quality: 'highestaudio',
highWaterMark: 262144,
}, opusEncoded: false,
fmt: 's16le',
encoderArgs: [],
seek: 0}).on("error", (err) => {
return err.message.toLowerCase().includes("premature close") ? null : console.log(err);

});

EPIPE error

I keep getting this error whenever I tried to use this library

events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at afterWriteDispatched (internal/stream_base_commons.js:156:25)
    at writeGeneric (internal/stream_base_commons.js:147:3)
    at Socket._writeGeneric (net.js:785:11)
    at Socket._write (net.js:797:8)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at Socket.Writable.write (internal/streams/writable.js:303:10)
    at PassThrough.ondata (internal/streams/readable.js:719:22)
    at PassThrough.emit (events.js:315:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
Emitted 'error' event on FFmpeg instance at:
    at FFmpeg.onerror (internal/streams/readable.js:760:14)
    at FFmpeg.emit (events.js:315:20)
    at Socket.processError (C:\Users\Thunderbolt XV\Desktop\SoundWave-dev-2.0.0\node_modules\prism-media\src\core\FFmpeg.js:64:40)
    at Socket.emit (events.js:315:20)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -4047,
  code: 'EPIPE',
  syscall: 'write'
}

Here is the code that is calling this package:

const stream = ytdlFallBack(song.url, {
				filter: "audioonly",
				encoderArgs: ["-af", `${queue.effects ?? "dynaudnorm=f=200"}`],
				//dlChunkSize: 0,
				opusEncoded: false,
				fmt: " mp3",
				//highWaterMark: 1 << 25,
				seek: seek || 0,
			});
			setTimeout(() => {
				let currentStream = queue.connection.play(stream, {
					type: "unknown",
					highWaterMark: 1,
				});
				currentStream.setVolumeLogarithmic(volume / 200);
				queue.dispatcher = currentStream;
				currentStream.on("finish", () => {
					if (!queue.repeatMode) {
						this.emit("songEnd", {
							initMessage: queue.initMessage,
							song: song,
						});
						queue.history = song;
						queue.effects = null;
					}
					try {
						queue.songs[0].seekTime = 0;
					} catch (e) {}
					return this.mainplayer(guildID, false);
				});
			}, 200);

Here are the dependencies that are installed:

{
    "@discordjs/opus": "^0.5.0",
    "auto-bind": "^4.0.0",
    "bufferutil": "^4.0.3",
    "discord-ytdl-core": "^5.0.2",
    "discord.js": "^12.5.3",
    "erlpack": "^0.1.3",
    "ffmpeg-static": "^4.3.0",
    "get-audio-duration": "^2.0.3",
    "get-urls": "^10.0.0",
    "libsodium-wrappers": "^0.7.9",
    "lyrics-finder": "^21.7.0",
    "node-cron": "^3.0.0",
    "readdir-enhanced": "^6.0.4",
    "slash-commands": "^1.4.0",
    "spotify-url-info": "^2.2.0",
    "utf-8-validate": "^5.0.4",
    "winston": "^3.3.3",
    "youtubei": "0.0.1-rc.14",
    "ytdl-core": "^4.5.0",
    "ytdl-core-discord": "^1.3.0",
    "ytpl": "^2.2.0",
    "ytsr": "^3.5.0",
    "zlib-sync": "^0.1.7"
  }

I have tried everything I can. Sometimes (very rarely) it works but most of the time it either just immediately ends or throws the said error.

Thanks in advance.

Certain encoderArgs throw errors

Heya - great job on the wrapper, super useful!

I wanted to be able to give a start & end time to a youtube clip but it's throwing errors that I'm not really able to interpret.

Here's the snippet:

  const ytdlContent = ytdl(song.url, {
      filter: 'audioonly',
      opusEncoded: true,
      encoderArgs: ['-ss', song.startTime, '-t', song.endTime]
    });
  
  const dispatcher = serverQueue.connection
    .play(ytdlContent, { type: 'opus' })
    .on('finish', () => {
      serverQueue.songs.shift();
      play(guild, serverQueue.songs[0]);
    })
    .on('error', (error) => console.error(err));

Where song.startTime & song.endTime look something like 2:30, 2:42.

Worth mentioning that only using the startTime works, eg:

 encoderArgs: ['-ss', song.startTime]
  • which is basically what the seek option you've added is doing under the hood anyway.

Wondering if you meant to add an end time but it was problematic - or am I just using ffmpeg wrong?
Here's the error thrown btw (it never gets to the .on( 'error') catch)

events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16)
Emitted 'error' event on FFmpeg instance at:
    at FFmpeg.onerror (internal/streams/readable.js:760:14)
    at FFmpeg.emit (events.js:315:20)
    at Socket.processError (/<pwd>/node_modules/prism-media/src/core/FFmpeg.js:65:40)
    at Socket.emit (events.js:315:20)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

TypeError: The compressed data passed is corrupted

I get this error with every created dispatchers on latest version (4.0.0)

...node_modules/.registry.npmjs.org/prism-media/1.2.2/node_modules/prism-media/src/opus/Opus.js:64
     return this.encoder.decode(buffer, Opus.name === 'opusscript' ? null : this._options.frameSize);
                         ^

 TypeError: The compressed data passed is corrupted
     at Decoder._decode (...node_modules/.registry.npmjs.org/prism-media/1.2.2/node_modules/prism-media/src/opus/Opus.js:64:25)
     at Decoder._transform (...node_modules/.registry.npmjs.org/prism-media/1.2.2/node_modules/prism-media/src/opus/Opus.js:189:20)
     at Decoder.Transform._read (_stream_transform.js:189:10)
     at Decoder.Transform._write (_stream_transform.js:177:12)
     at doWrite (_stream_writable.js:417:12)
     at writeOrBuffer (_stream_writable.js:401:5)
     at Decoder.Writable.write (_stream_writable.js:301:11)
     at Socket.ondata (_stream_readable.js:696:22)
     at Socket.emit (events.js:196:13)
     at addChunk (_stream_readable.js:290:12)

On 2.0.1 version everything works fine

Laggy music

Im having a issue with a bot, the music is speeding up or lagging
Has anyone had any type of issue like this?

Error!

throw new Error('FFmpeg/avconv not found!');
^

Error: FFmpeg/avconv not found!

uh im doing the download won

Armv6 fatal error on opus encoder

I'm trying to run a music discord bot on my raspberry pi zero but when I try to play anything i get a fatal error:
Liftoff bailout should not happen. Cause: Armv6 not supported
Im using the last version of discord-ytdl-core and the last version of discord-opus, node 16.9.1.
It's this error posible to solve?

Can't use on docker

I can use it play music on my local

node test.js

but can't use in docker, bot join and leave voice channel

docker-compose -f docker-compose.test.yml

test.js

const ytdl = require('discord-ytdl-core')
const Discord = require('discord.js')
const client = new Discord.Client()
const BOT_TOKEN = require('./config/TOKEN')

client.on('ready', () => {
  console.log('ready')
})

client.on('message', (msg) => {
  if (msg.author.bot || !msg.guild) return
  if (msg.content === '#!play') {
    if (!msg.member.voice.channel)
      return msg.channel.send("You're not in a voice channel?")
    let stream = ytdl('https://www.youtube.com/watch?v=QnL5P0tFkwM', {
      filter: 'audioonly',
      opusEncoded: false,
      fmt: 'mp3',
      encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200'],
    })
    //console.log(stream)

    msg.member.voice.channel
      .join()
      .then((connection) => {
        let dispatcher = connection
          .play(stream, {
            type: 'unknown',
          })
          .on('finish', () => {
            msg.guild.me.voice.channel.leave()
          })
      })
      .catch((e) => {
        console.log(e)
      })
  }
})
client.login(BOT_TOKEN)

Dockerfile

FROM node
WORKDIR /bot_app
COPY package.json . 
RUN apt-get update
RUN apt-get install ffmpeg -y
ARG NODE_ENV
RUN if [ "$NODE_ENV" = "development" ]; \
    then npm install; \
    else npm install --only=production; \
    fi
COPY . ./
ENV PORT 3000
EXPOSE $PORT

docker-compose.test.yml

version: '3'
services:
  node-app:
    build:
      context: .
      args:
        NODE_ENV: development
    volumes:
      - ./:/bot_app:ro
      - /app/node_modules
    environment:
      - NODE_ENV=development
    # package.js->:"test": "nodemon test.js"
    command: npm run test

dependencies

"dependencies": {
    "discord-ytdl-core": "^5.0.3",
    "discord.js": "^12.2.0",
    "express": "^4.17.1",
    "mongoose": "^5.12.12",
    "node-fetch": "^2.6.1",
    "ytdl-core": "^4.8.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }

Error

Cannot play live stream video

MinigetError: input stream: Status code: 404

error from this line const songInfo = await ytdl.getInfo(args[1]) , args[1] is song url

MinigetError: Status code: 404
    at ClientRequest.<anonymous> (/app/node_modules/miniget/dist/index.js:210:27)
    at Object.onceWrapper (node:events:514:26)
    at ClientRequest.emit (node:events:394:28)
    at HTTPParser.parserOnIncomingClient (node:_http_client:621:27)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:127:17)
    at TLSSocket.socketOnData (node:_http_client:487:22)
    at TLSSocket.emit (node:events:394:28)
    at addChunk (node:internal/streams/readable:312:12)
    at readableAddChunk (node:internal/streams/readable:287:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:226:10)
    at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23) {
  statusCode: 404
}
/app/node_modules/discord.js/src/rest/RequestHandler.js:170
          return reject(new DiscordAPIError(request.path, data, request.method, res.status));
                        ^

DiscordAPIError: Cannot send an empty message
    at RequestHandler.execute (/app/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  method: 'post',
  path: '/channels/802691580095234048/messages',
  code: 50006,
  httpStatus: 400
}

Errows thrown by ytdl aren't bubbling up

ytdl-core currently has a JSON parse issue, which when triggered crashes the app with no way of capturing it. This isn't an issue when using ytdl-core directly.

Reproduce:
Add an .on("error") event to the discord-ytdl-core stream.
Modify ytdl-core's lib/info.js file and add the following on line 63: throw new Error("Test")
Now run, ytdl-core should throw an error and you will see it's not captured by discord-ytdl-core.

highWaterMark value stuck at 16kb's.

Hey, I'm currently using this code to change the value of highWaterMark in my ytdl stream for my discord bot, and it works when using ytdl-core, and used to work with discord-ytdl-core. Unfortunately, as of recent, this code no longer works, and the music will cut out in discord, but the stream will continue to run, due to highWaterMark being at 16kb's, and I'm no longer able to increase it for some reason. Here's my code:

function play(message, guild, song) {
    const { queue } = require("../index");
    const serverQueue = queue.get(guild.id);
    if (!song) {
        serverQueue.songs = [];
        queue.delete(guild.id);
        return message.guild.me.voice.channel.leave();
    };
    const ytdl = require("discord-ytdl-core");
    let encoderArgs = [`aresample=48000`];
    let encoderArgsString = "";
    if (serverQueue.nightcore == true) encoderArgs.push(`asetrate=${serverQueue.asetrate}`);
    if (serverQueue.speed != 1) encoderArgs.push(`atempo=${serverQueue.speed}`);
    encoderArgs.push(`atrim=start=${serverQueue.seek/1000}`);
    if (serverQueue.bass != 0) encoderArgs.push(`bass=g=${serverQueue.bass}`);
    if (serverQueue.pitch != 1) encoderArgs.push(`rubberband=pitch=${serverQueue.pitch}`);
    if (serverQueue.eightd != 0) encoderArgs.push(`apulsator=hz=${serverQueue.eightd}`);
    encoderArgsString = encoderArgs.join(", ");
    encoderArgs = ["-af", `${encoderArgsString}`];
    const fs = require("fs");
    const config = JSON.parse(fs.readFileSync("././config.json", "utf-8"));
    serverQueue.stream = ytdl(song.url, {
        requestOptions: {
            headers: {
                cookie: config.COOKIES,
                "x-youtube-identity-token": config.YTIDTOKEN
            }
        },
        filter: "audioonly",
        opusEncoded: true,
        dlChunkSize: 0,
        highWaterMark: 1<<25,
        encoderArgs: encoderArgs
    });
    const dispatcher = serverQueue.connection.play(serverQueue.stream, {
        type: "opus"
    }).on("finish", () => {
        serverQueue.stream.destroy();
        if (serverQueue.filterCmd == false) {
            if (!serverQueue.loop) serverQueue.songs.shift();
            serverQueue.curtime = 0;
            serverQueue.seek = 0;
        };
        serverQueue.filterCmd = false;
        play(message, guild, serverQueue.songs[0]);
    }).on("error", (error) => {
        serverQueue.stream.destroy();
        serverQueue.songs = [];
        queue.delete(guild.id);
        console.log(error);
        return message.react("โŒ");
    });
    dispatcher.setVolume(0.25);
    const npembed = require("../embeds/npembed");
    npembed.execute(message);
};

return module.exports.play = play;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.