0

Does anyone know how to loop the same source in FFmpeg?

This is my code:

@bot.command(pass_context = True)
async def join(ctx):

if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()
    source = FFmpegPCMAudio('test.mp3')
    player = voice.play(source)
else:
    await ctx.send('You need to be in a Voice-Channel.')

I want the audio-file "test.mp3" looped permanently. I've searched on the internet but all the results given there were outdated.

LordLazor
  • 39
  • 1
  • 7
  • Maybe you can find answers [here](https://stackoverflow.com/questions/62457834/how-to-make-a-discord-bot-loop-audio-discord-py) – CaptAngryEyes Apr 06 '21 at 06:26

2 Answers2

1

Here is a way to know when a song has finished playing.

if (ctx.author.voice):
    finished = False 
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: finished = True)

Using the lambda function you can implement a loop structure to replay the song once finished.

Alex Wang
  • 27
  • 2
  • 7
0

Here's a solution I'm currently using for myself:

async def play_source(voice_client):
    source = FFmpegPCMAudio("test.mp3")
    voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else bot.loop.create_task(play_source(voice_client)))

This solution is just a basic one. After the source is completed, it starts again with the same voice_client.

If the audio starts to speed up at the beginning then just put a await asyncio.sleep(0.5) between the source and the voice_client.play.

To start it in the first place, just replace your code like this:

@bot.command(pass_context = True)
async def join(ctx):

if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()
    bot.loop.create_task(play_source(voice))
else:
    await ctx.send('You need to be in a Voice-Channel.')
dieserniko
  • 121
  • 7