Python Discord Bot: Simultaneous Audio Playback

I’m working on a Discord bot and I want it to play a short sound effect while music is already playing. So far I haven’t had any luck.

I tried using the play_sound method while music was playing through create_audio_source, but it just made a weird noise instead of playing the sound file properly.

Here’s what I’ve tried:

async def play_effect(self, msg):
    channel = msg.author.voice.channel
    audio = await self.join_voice(channel)
    audio.play_sound('sfx/beep.wav')

Is it even possible for a Discord bot to play two audio files at the same time? Any help would be great!

Playing multiple audio streams simultaneously in Discord bots is challenging because of inherent library limitations. Instead of attempting to output two separate streams, a more reliable approach is to pre-mix the audio files. For example, you can use pydub to overlay your sound effect onto the music track. First, load both audio files using pydub and overlay the sound effect onto the background music at the desired moment. Then export the resulting mixed audio as a new file and have your bot play that file. This method generally avoids conflicts with Discord’s audio handling even if it requires additional processing time.

i tried mixing audio rather than playing two streams at once. try using pydub to overlay your effect on the music:

from pydub import AudioSegment
music = AudioSegment.from_file('music.mp3')
effect = AudioSegment.from_file('beep.wav')
mixed = music.overlay(effect)
mixed.export('output.mp3', format='mp3')

then play the mixed file. might work better.

Hey there, Jack81! I’ve actually tackled this issue before in one of my projects. The thing is, Discord’s audio system isn’t really built for playing multiple streams simultaneously. What worked for me was pre-mixing the audio files.

Here’s what I did:

I used the pydub library to combine my background music and sound effects into a single audio file. It’s pretty straightforward - you load both audio files, overlay the sound effect on the music at the right moment, and export it as a new file.

Then, I just had my bot play this new, combined audio file. It solved the issue of trying to play two streams at once and gave me much better control over timing and volume levels.

One tip: if you need to add sound effects dynamically, you might want to look into creating a simple audio mixing function that you can call on the fly. This way, you can generate the mixed audio just before playing it, giving you more flexibility.

Hope this helps! Let me know if you need any more details on implementation.