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

Stopping Audio Playback #181

Open
rGunti opened this issue Aug 5, 2017 · 18 comments
Open

Stopping Audio Playback #181

rGunti opened this issue Aug 5, 2017 · 18 comments

Comments

@rGunti
Copy link

rGunti commented Aug 5, 2017

I used the example here to send Audio files. Now I wanted to implement a Skip command which stops the current playback and starts the next one. But I don't really know how to do that with the methods provided.

I tried stopping the stream but then the socket closes and the app crashes with this error:

Debugger attached.
events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: This socket is closed
    at Socket._writeGeneric (net.js:721:18)
    at Socket._write (net.js:781:8)
    at doWrite (_stream_writable.js:371:12)
    at clearBuffer (_stream_writable.js:497:7)
    at onwrite (_stream_writable.js:423:7)
    at WriteWrap.afterWrite [as oncomplete] (net.js:863:12)
@izy521
Copy link
Owner

izy521 commented Aug 5, 2017

What's your code for doing this?

@jorenvandeweyer
Copy link

jorenvandeweyer commented Aug 16, 2017

bot.getAudioContext(voiceChannel, function(err, stream){ stream.stop(); });

@izy521
Copy link
Owner

izy521 commented Aug 17, 2017

I'm not sure PR #186 fixes this issue. It sounds like he's not keeping the stream open, but he hasn't posted his code, so I can't proceed until then.

@Jays2Kings
Copy link

Jays2Kings commented Sep 4, 2017

I'm having a similar issue of trying to stop. #186 doesn't fix it. When the bot leaves the channel or stops the stream while an audio file is playing, I get that same error. I'm not sure how to go about safely stopping the file stream before exiting the voice channel.

var startAudio = function ()
{
	bot.getAudioContext(VCID, function (error, stream) {
		//Once again, check to see if any errors exist
		if (error) return console.error(error);
		//filePath is just the js's path + "/"
		currentlyPlaying = fs.createReadStream(filePath + "Music/" + fs.readdirSync(filePath + "Music")[SongChoice])
		//Without {end: false}, it would close up the stream, so make sure to include that.
		currentlyPlaying.pipe(stream, { end: false });
		if (error) return console.error(error);
		
		//The stream fires `done` when it's got nothing else to send to Discord.
		stream.on('done', function () {
			bot.leaveVoiceChannel(VCID); //this exits fine with no crashes 
		});                        			
	});
}
  
var StopAudio = function()
{
	bot.leaveVoiceChannel(VCID); //method call caused socket to close and crash the bot if stream is still playing
}

@izy521
Copy link
Owner

izy521 commented Sep 4, 2017

Your issue is just because you're leaving the channel without .stop()ing the stream. His issue sounds like he's not keeping the stream open, yet trying to send more data after its closed.

@izy521 izy521 closed this as completed Sep 4, 2017
@Jays2Kings
Copy link

I've tried both leaving the channel and only stopping the stream without leaving the channel via bot.getAudioContext(VCID, function (err, stream) { stream.stop(); }); but the socket gets closed either way.

@izy521
Copy link
Owner

izy521 commented Sep 4, 2017

What do you mean the socket gets closed?

@Jays2Kings
Copy link

I mean that the socket is closed when I stop the stream, resulting in a crash. I get a similar error to rGunti

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

Error: This socket is closed
    at Socket._writeGeneric (net.js:679:19)
    at Socket._write (net.js:730:8)
    at doWrite (_stream_writable.js:331:12)
    at clearBuffer (_stream_writable.js:438:7)
    at onwrite (_stream_writable.js:370:7)
    at Socket.WritableState.onwrite (_stream_writable.js:90:5)
    at WriteWrap.afterWrite (net.js:812:12)

@izy521
Copy link
Owner

izy521 commented Sep 4, 2017

What's your code? I'm heading to sleep, I'll check in the morning.

@izy521 izy521 reopened this Sep 4, 2017
@Jays2Kings
Copy link

Jays2Kings commented Sep 4, 2017

I've redacted the userIDs and voice channel id, but aside from that this is the same code that crashes when I stop the stream.

var Discord = require('discord.io');
var bot = new Discord.Client({
    autorun: true,
    token: ""
});

var filePath = "";
var fs = require("fs"), path = require('path'), util = require('util');
var firstrun = true;
var currentlyPlaying;
var danZoneStarterIDs = ["", "", "", ""];
var danZoneTime = false;
var danZoneTimeRunning = false;
var danZoneSongChoice = 0;
var VCID = '';
bot.on('ready', function (event) {
    console.log('Logged in as %s - %s\n', bot.username, bot.id);
    if (firstrun) { 
        filePath = __dirname + "/";
        firstrun = false;
    }
});

// Automatically reconnect if the bot disconnects due to inactivity
bot.on('disconnect', function (erMsg, code) {
    console.log(bot.userName + ' disconnected from Discord with code ' + code + ' for reason: ' + erMsg);
    bot.connect();
});

bot.on('message', function (user, userID, channelID, text, event) {
    if (userID != bot.id) {        
        if (danZoneStarterIDs.indexOf(userID) > -1) {
            if (!danZoneTime && text.toLowerCase() == "!join") {
                danZoneTime = true;
                var files = fs.readdirSync(filePath + "Dan Zone Music");
                danZoneSongChoice = Math.floor(Math.random() * files.length);
                bot.sendMessage({ to: channelID, message: "Joining Channel" });
                bot.joinVoiceChannel(VCID, function (error, events) {
                    //Check to see if any errors happen while joining.
                    if (error) return console.error(error);
                });
            }
            else if (!danZoneTimeRunning && danZoneTime && text.toLowerCase().indexOf("!start") == 0) {
                danZoneTimeRunning = true;
                //Then get the audio context
                bot.getAudioContext(VCID, function (error, stream) {
                    //Once again, check to see if any errors exist
                    if (error) return console.error(error);
                    bot.sendMessage({ to: channelID, message: "Now Playing: \"" + fs.readdirSync(filePath + "Dan Zone Music")[danZoneSongChoice].split('.')[0] + "\"" });
                    currentlyPlaying = fs.createReadStream(filePath + "Dan Zone Music/" + fs.readdirSync(filePath + "Dan Zone Music")[danZoneSongChoice])
                    //Without {end: false}, it would close up the stream, so make sure to include that.
                    currentlyPlaying.pipe(stream, { end: false });
                    if (error) return console.error(error);

                    //The stream fires `done` when it's got nothing else to send to Discord.
                    stream.on('done', function () {
                        if (danZoneTime) {
                            bot.leaveVoiceChannel(VCID);
                            danZoneTimeRunning = false;
                            danZoneTime = false;
                            bot.sendMessage({ to: channelID, message: "Finished Playing" });
                        }
                        //Handle
                    });
                    if (error) return console.error(error);
                });
            }
            else if (danZoneTimeRunning && text.toLowerCase() == "!stop") {
                danZoneTime = false;
                danZoneTimeRunning = false;
                bot.getAudioContext(VCID, function (err, stream) {
                    stream.stop();
                }); //causes crash if stream is playing something
                bot.sendMessage({ to: channelID, message: "Stopped" });
            }
            else if (text.toLowerCase() == "!leave") {
                bot.leaveVoiceChannel(VCID);
            }
        }
    }
});

@izy521
Copy link
Owner

izy521 commented Sep 4, 2017

Try making the stream variable public after your first getAudioContext then referring to it again, instead of calling getAudioContext twice.

@Jays2Kings
Copy link

Jays2Kings commented Sep 4, 2017

Still no luck, same error. when creating a var currentStream; setting it to currentStream = stream; the first time i call getAudioContext() in "!start" and in my "!stop" command i removed the getAudioContext() with

 currentlyPlaying.unpipe(currentStream);
  setTimeout(function () {
       currentStream.stop();
  }, 2000);

I've tried without the setTimeout, setting currentStream to null afterward, not unpiping the filestream, all results in the same crash.

@izy521
Copy link
Owner

izy521 commented Sep 4, 2017

Alright, that's weird, I'll check it out later on today when I have the time, but I wish Node error's weren't so generic at times. Sounds like it's a clear issue in the back-end due to some change on Discord's side, but I'm not sure where.

@DecibillyJoel
Copy link
Contributor

DecibillyJoel commented Sep 21, 2017

Have you tried adding an error handler to the stream?

...
bot.getAudioContext(VCID, function (error, stream) {
    //Once again, check to see if any errors exist
    if (error) return console.error(error);
    stream.on('error',function(err){console.log("AudioContext Error:",err)});
...

@googleboy360
Copy link

googleboy360 commented Nov 26, 2017

I know i have when i was using it. Didn't get any error from it though | Didn't stop it from crashing. Socket closed error anyways. Only happened when the bot left.

@tymmesyde
Copy link

Still no update on this ?

@Kyuraa
Copy link

Kyuraa commented Aug 27, 2018

Any update on this?

@YunusEmrahDursun
Copy link

YunusEmrahDursun commented Nov 25, 2018

@rGunti i solve by like this : i create a start.js https://github.com/DeliDoktoru/FenomenDiscordBot/blob/master/start.js this js is a parent process. when discord bot died, calls again

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants