如何让Discord Bot播放YouTube音频?高中生项目求助
Hey there! I totally get how frustrating it is when you’re working on a final project and can’t get a Discord bot’s audio playback to work—especially when existing tutorials fall flat. Let’s walk through fixing your local MP3 code first, then add YouTube playback functionality step by step.
First, let’s correct your existing MP3 playback code—there are a few outdated syntax issues specific to the Discord.py Rewrite version that were breaking it:
1. Corrected Local MP3 Playback Code
Your original code used old attribute names and didn’t properly create an audio source object. Here’s the fixed version:
import discord from discord.ext import commands import asyncio @bot.command() async def mp3play(ctx): user = ctx.message.author # Rewrite uses `user.voice.channel` instead of `voice_channel` voice_channel = user.voice.channel if voice_channel is not None: # Connect directly to the voice channel object vc = await voice_channel.connect() # Create a valid audio source from your MP3 file audio_source = discord.FFmpegPCMAudio("holder.mp3") # Play the audio and add basic completion feedback vc.play(audio_source, after=lambda e: print(f"Playback done: {e}" if e else "Complete!")) # Wait for playback to finish before disconnecting while vc.is_playing(): await asyncio.sleep(1) await vc.disconnect() else: await ctx.send("You need to be in a voice channel to use this command!")
Important note: You’ll need FFmpeg installed on your system for this to work. Add it to your system PATH, or specify the full path to the executable like this:discord.FFmpegPCMAudio("holder.mp3", executable="C:/ffmpeg/bin/ffmpeg.exe") (adjust for your OS/path).
2. Adding YouTube Audio Playback
To play audio from YouTube links, we’ll use yt-dlp (a maintained, reliable fork of youtube-dl) to fetch the audio stream, then feed it to FFmpeg. Here’s how to set it up:
Step 1: Install Required Packages
Run these in your terminal to get the tools you need:
pip install yt-dlp pip install discord.py[voice] # Ensures full voice support is enabled
Step 2: YouTube Playback Command Code
Add this to your bot script to handle YouTube links:
import yt_dlp # Configure yt-dlp to fetch only high-quality audio ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'quiet': True, 'no_warnings': True, } @bot.command() async def play(ctx, *, url): user = ctx.message.author voice_channel = user.voice.channel if voice_channel is None: await ctx.send("Join a voice channel first!") return # Connect to the user's voice channel vc = await voice_channel.connect() # Fetch the audio stream URL from YouTube with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=False) audio_url = info['url'] # Create the audio source from the YouTube stream audio_source = discord.FFmpegPCMAudio(audio_url, executable="ffmpeg") # Add your FFmpeg path if needed # Start playback and add error feedback vc.play(audio_source, after=lambda e: print(f"Playback error: {e}" if e else "YouTube playback finished!")) # Wait for playback to end, then disconnect while vc.is_playing(): await asyncio.sleep(1) await vc.disconnect()
Quick Troubleshooting Tips
- FFmpeg not found: Double-check FFmpeg is installed and in your PATH, or use the full executable path in the code.
- Bot can’t connect to voice: Make sure your bot has the
ConnectandSpeakpermissions in the voice channel. - Choppy playback: Lower the
preferredqualityvalue in the yt-dlp options, or check your internet connection.
内容的提问来源于stack exchange,提问作者Allen Rowland

