Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When playing audio, the last part is cut off. How can this be fixed? (discord.py)

I have a bot I am producing and I have figured out how to make it play audio from youtube. The audio is streamed so the files are not downloaded to my PC. Here is my code:

@bot.command(name='play', aliases=['p'], help='Plays a song.')
async def play(ctx, url):
    channel = ctx.message.author.voice.channel
    if ctx.guild.voice_client is None:
        await channel.connect()
    client = ctx.guild.voice_client
    player = await YTDLSource.from_url(url, stream = True)
    ctx.voice_client.play(player)
    await ctx.send('Now Playing: {}'.format(player.title))

I am using some code that is not shown in this block because it is part of the basic_voice.py package (found here: https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py, I am using lines 12-52). My issue is that the audio is cut off at the end, with the FFMPEG window closing on my PC. This happened when I tested local files on my PC as well. I am not sure why FFMPEG just closes early, but I'd like a fix to it if possible. Also, if it's important, the amount cut off at the end is dependant on the length of the audio being played. The player works with no lag, it just mysteriously stops.

like image 367
Tico Lobo Avatar asked Nov 22 '25 15:11

Tico Lobo


1 Answers

This is a known issue when you try to make a bot which doesn't download the song it's playing. It is explained here : https://support.discord.com/hc/en-us/articles/360035010351--Known-Issue-Music-Bots-Not-Playing-Music-From-Certain-Sources

To solve the problem, you can use the FFmpegPCMAudio method from discord.py and give specific options so the bot will be able to reconnect and continue to play the video :

ydl_opts = {'format': 'bestaudio'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

@bot.command(name='play', aliases=['p'], help='Plays a song.')
async def play(ctx, url):
    channel = ctx.message.author.voice.channel
    voice = get(self.bot.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
    
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            source = ydl.extract_info(url, download=False)['formats'][0]['url']

    voice.play(discord.FFmpegPCMAudio(song['source'], **FFMPEG_OPTIONS))
    voice.is_playing
like image 124
MrSpaar Avatar answered Nov 24 '25 04:11

MrSpaar