To play an audio file in Python, you can use several libraries, with pygame, pydub, and simpleaudio being popular choices. However, for playing an .mp3 file, pygame is a straightforward and simple option. If you haven't installed pygame yet, you can do so by running pip install pygame in your terminal or command prompt.
Here's a simple example of how to play an .mp3 file using pygame:
python
import pygame
def play_audio(file_path):
"""
Play an audio file.
Parameters:
- file_path: str, path to the audio file to be played.
"""
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
# Wait for the audio to finish playing
pygame.time.Clock().tick(10)
if __name__ == "__main__":
audio_file_path = "/media/dulu/PART2HDD/VS_Code_Projects/play_beep/Beep.mp3"
play_audio(audio_file_path)
This script initializes the pygame mixer, loads the specified .mp3 file, and plays it. The while loop is used to keep the script running until the audio has finished playing, as pygame.mixer.music.play() is non-blocking.
Alternative: Using pydub
If you're interested in manipulating audio or prefer using pydub, you can play an .mp3 file like so:
First, install pydub and ffmpeg (as pydub relies on it for some operations). You can install pydub via pip: pip install pydub. For ffmpeg, follow the installation instructions on the FFmpeg website.
Then, use the following Python code:
python
from pydub import AudioSegment
from pydub.playback import play
def play_audio(file_path):
"""
Play an audio file.
Parameters:
- file_path: str, path to the audio file to be played.
"""
song = AudioSegment.from_mp3(file_path)
play(song)
if __name__ == "__main__":
audio_file_path = "/media/dulu/PART2HDD/VS_Code_Projects/play_beep/Beep.mp3"
play_audio(audio_file_path)
This will load the .mp3 file using pydub and play it.
Choosing a Library
Use pygame for simple cases where you just need to play audio files. It's straightforward and doesn't require additional dependencies beyond what's installable via pip.
Consider pydub if you're also interested in manipulating audio (e.g., slicing, concatenating, or applying effects to audio segments).
Both examples should work for playing your .mp3 file. Choose the one that best fits your project's needs.