如何在Pydub中加载音频?新手遇文件找不到及播放异常问题
Hey there! Let's work through your two Pydub problems one by one—they're both super common, so we'll get you sorted quickly.
1. Resolving the FileNotFoundError for MP3 Files
The error you're seeing usually boils down to two easy-to-miss issues:
Double-check your file path & working directory
Even if you thinksong.mp3is in the same folder as your script, your Python interpreter might be running from a different working directory. To confirm, add this to your script and run it:import os print("Current working directory:", os.getcwd())If the output doesn't match the folder where
song.mp3lives, either move the MP3 file to that directory, or use an absolute file path in your code (e.g.,AudioSegment.from_mp3("C:/Users/YourName/Projects/your-folder/song.mp3")).Install FFmpeg (critical for MP3 support)
Pydub doesn't handle MP3 decoding on its own—it relies on FFmpeg under the hood. If you haven't installed it yet:- Download FFmpeg's Windows build from its official site
- Extract the files, then add the
binfolder (whereffmpeg.exeis located) to your system'sPATHenvironment variable - Restart your code editor/terminal so the PATH changes take effect
Alternatively, you can specify the FFmpeg path directly in your script:
from pydub import AudioSegment AudioSegment.converter = "C:/path/to/ffmpeg/bin/ffmpeg.exe"
2. Fixing Wav Playback Glitches & Chrome Audio Errors
The weird static and Chrome's audio rendering error are likely related to PyAudio's interaction with your system's audio devices. Here's how to fix it:
Switch to SimpleAudio instead of PyAudio
PyAudio can sometimes lock up audio devices or cause compatibility issues. SimpleAudio is a more lightweight, system-friendly alternative for playback. Install it first:pip install simpleaudioThen modify your playback code—Pydub should automatically use SimpleAudio if it's installed, but you can force it explicitly:
from pydub import AudioSegment from pydub.playback import play music = AudioSegment.from_wav("test.wav") play(music, player="simpleaudio")Verify your WAV file is valid
Corrupted or non-standard WAV files can cause static. Use a tool like Audacity to open the file, then export it as a standard WAV (44100 Hz sample rate, 16-bit depth) and try playing that version.Check for audio device conflicts
Make sure no other apps are using exclusive control of your audio devices. Go to Windows Sound Settings > Sound Control Panel > Select your playback device > Properties > Advanced, then uncheck "Allow applications to take exclusive control of this device". This prevents apps like Pydub from hogging the audio system and breaking Chrome.
内容的提问来源于stack exchange,提问作者LumaCurve

