Discord接收音频

Discord receive audio

我想从 Discord 接收音频以进行语音识别。我在 python Discord APi 中没有找到任何内容。语音识别没有问题,但我不知道如何从 Discord 接收音频。也许有人可以帮助我。

这个功能实际上并不存在。有一个VoiceClient.poll_voice_ws coroutine, but that just reads directly from the socket。您必须想出一些方法将其解码为音频并自己进一步处理它。

最近对 discord.py 分支 pycord 的更新增加了录制音频的可能性,然后您可以将其用于语音识别。 要开始录制音频,您只需使用 Sink 调用 VoiceClient.start_recording,一个将在您停止录制后调用的函数,以及该函数的可选参数。一个例子是:

import discord

bot = discord.Bot(debug_guilds=[719996466290098180])

@bot.command()
async def start_record(ctx):
    await ctx.author.voice.channel.connect() # Connect to the voice channel of the author
    ctx.voice_client.start_recording(discord.sinks.MP3Sink(), finished_callback, ctx) # Start the recording
    await ctx.respond("Recording...") 

async def finished_callback(sink, ctx):
    # Here you can access the recorded files:
    recorded_users = [
        f"<@{user_id}>"
        for user_id, audio in sink.audio_data.items()
    ]
    files = [discord.File(audio.file, f"{user_id}.{sink.encoding}") for user_id, audio in sink.audio_data.items()]
    await ctx.channel.send(f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files) 

@bot.command()
async def stop_recording(ctx):
    ctx.voice_client.stop_recording() # Stop the recording, finished_callback will shortly after be called
    await ctx.respond("Stopped!")


bot.run(Token)

因为这不是音频流,所以你不能用它来做一个会自动听你说话的虚拟助手,但你可以录制语音通道并得到里面说了什么。