如何集成 PyAudio 和 discord.py 以从我的麦克风播放音频
How to integrate PyAudio and discord.py to play audio from my microphone
不知道怎么回事
当我在我的 discord 服务器上调用 voice_test
命令时,机器人加入了一个语音频道,它的轮廓变成绿色但我什么也没听到。
虽然 运行 代码,但我没有回溯。
这是代码:
CHUNK = 2048
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
@client.command()
async def voice_test(ctx, *, channel: discord.VoiceChannel):
if ctx.voice_client is not None:
vc = await ctx.voice_client.move_to(channel)
else:
vc = await channel.connect()
p = pyaudio.PyAudio()
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK
)
while vc.is_connected():
data = stream.read(CHUNK)
vc.send_audio_packet(data, encode=False)
#print(data)
print('done playing',file=sys.stderr)
stream.stop_stream()
stream.close()
p.terminate()
根据我自己最近的经验,您遇到了几个问题,但归结为 discord 需要 20 毫秒的 48000hz 双通道 opus 编码音频。
如果您在调用 send_audio_packet 之前将音频编码为 opus,您将开始听到声音。声音不好,但声音。
经过多次迭代和反复试验,这对我有用。
class PyAudioPCM(discord.AudioSource):
def __init__(self, channels=2, rate=48000, chunk=960, input_device=1) -> None:
p = pyaudio.PyAudio()
self.chunks = chunk
self.input_stream = p.open(format=pyaudio.paInt16, channels=channels, rate=rate, input=True, input_device_index=input_device, frames_per_buffer=chunk)
def read(self) -> bytes:
return self.input_stream.read(self.chunks)
async def play_audio_in_voice():
vc.play(PyAudioPCM(), after=lambda e: print(f'Player error: {e}') if e else None)
不知道怎么回事
当我在我的 discord 服务器上调用voice_test
命令时,机器人加入了一个语音频道,它的轮廓变成绿色但我什么也没听到。虽然 运行 代码,但我没有回溯。
这是代码:
CHUNK = 2048
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
@client.command()
async def voice_test(ctx, *, channel: discord.VoiceChannel):
if ctx.voice_client is not None:
vc = await ctx.voice_client.move_to(channel)
else:
vc = await channel.connect()
p = pyaudio.PyAudio()
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK
)
while vc.is_connected():
data = stream.read(CHUNK)
vc.send_audio_packet(data, encode=False)
#print(data)
print('done playing',file=sys.stderr)
stream.stop_stream()
stream.close()
p.terminate()
根据我自己最近的经验,您遇到了几个问题,但归结为 discord 需要 20 毫秒的 48000hz 双通道 opus 编码音频。
如果您在调用 send_audio_packet 之前将音频编码为 opus,您将开始听到声音。声音不好,但声音。
经过多次迭代和反复试验,这对我有用。
class PyAudioPCM(discord.AudioSource):
def __init__(self, channels=2, rate=48000, chunk=960, input_device=1) -> None:
p = pyaudio.PyAudio()
self.chunks = chunk
self.input_stream = p.open(format=pyaudio.paInt16, channels=channels, rate=rate, input=True, input_device_index=input_device, frames_per_buffer=chunk)
def read(self) -> bytes:
return self.input_stream.read(self.chunks)
async def play_audio_in_voice():
vc.play(PyAudioPCM(), after=lambda e: print(f'Player error: {e}') if e else None)