Introduction
Pyaudio allows us to play and record sounds with Python. To play MP3, however, we first need to convert the MP3 file to WAV format with ffmpeg. To use ffmpeg in Python, we use an interface tool called Pydub, which directly calls our ffmpeg executable and integrates with Pyaudio.
Installation
pip install pyaudio
pip install pydub
Playing sound
from pydub import AudioSegment
song = AudioSegment.from_mp3('test.mp3')
play(song)
If ffmpeg isn't installed on the machine, AudioSegment will fail to locate the mp3 file. There are a few solutions:
- Install ffmpeg and add to environment path
- Copy ffmpeg to the same folder as the python file
- Static link ffmpeg to pydub
Let's talk about the third option.
Static linking ffmpeg
By static linking ffmpeg, our program would be portable: users would not need to manually install ffmpeg to their OS.
Download ffmpeg and copy it to your script directory.
import os
import platform
from pathlib import Path
from pydub import AudioSegment
AudioSegment.ffmpeg = path_to_ffmpeg()
platform_name = platform.system()
if platform_name == 'Windows':
os.environ["PATH"] += os.pathsep + str(Path(path_to_ffmpeg()).parent)
else:
os.environ["LD_LIBRARY_PATH"] += ":" + str(Path(path_to_ffmpeg()).parent)
def path_to_ffmpeg():
SCRIPT_DIR = Path(__file__).parent
if platform_name == 'Windows':
return str(Path(SCRIPT_DIR, "win", "ffmpeg", "ffmpeg.exe"))
elif platform_name == 'Darwin':
return str(Path(SCRIPT_DIR, "mac", "ffmpeg", "ffmpeg"))
else:
return str(Path(SCRIPT_DIR, "linux", "ffmpeg", "ffmpeg"))
song = AudioSegment.from_mp3('test')
play(song)
The program should now be able to run and play the mp3 file. The path added to os environment is temporary and would be gone when the python program is completed.
Top comments (2)
Great, you can get free mp3 o wav from free-sound-effects.net/
Nice, just to mention the
play()
comes frompydub.playback
.