Discord bot audio playback issue when users join voice channel after bot connection

Discord Bot Audio Problem

I’m working on a Discord bot project to help out a disabled friend. The bot is supposed to play an audio file whenever someone joins a voice channel. The main issue I’m facing is that the audio only plays for people who were already in the voice channel before my bot connected. Anyone who joins the channel after the bot has already connected can’t hear the audio at all.

Bot Connection Code

if audio_client:
    await audio_client.disconnect()
try:
    target_channel = ctx.author.voice.channel
except AttributeError:
    await ctx.channel.send('Error: User not in valid voice channel')
audio_client = await target_channel.connect(reconnect=False)

Audio Playback Code

if audio_client:
    sound_file = await discord.FFmpegOpusAudio.from_probe('welcome.mp3')
    audio_client.play(sound_file)
    while audio_client.is_playing():
        continue

Has anyone encountered this before? What might be causing this behavior and how can I make sure all users hear the audio regardless of when they join?

I encountered a similar issue with my music bot recently. It seems that Discord handles existing members differently from those who join afterwards, causing audio playback problems. One effective approach is to avoid using from_probe() and instead create a new audio source just before each playback event. Additionally, always check the bot’s connection status using audio_client.is_connected() prior to playing audio. It’s also crucial to verify that the bot has the necessary permissions in the voice channel, as insufficient permissions can lead to audio issues for some users.

sounds like a timing issue. try adding a small delay before playin the audio - asyncio.sleep(0.5) works well. discord needs time 2 establish the connection when users join after the bot’s already there. also double-check ur audio file’s buffered properly.

Indeed, you are facing a common issue with Discord audio playback. When users join after your bot is connected, they may not receive the audio stream properly due to a missing audio context initialization. I’ve experienced this problem myself in the past. To address it, consider implementing an event listener for voice state updates. This can trigger your bot to send an audio stream to newly joined users. Alternatively, you could create a mechanism that waits until all users are connected before the audio starts playing. Both methods can effectively ensure late joiners receive the audio without issue.