How can MP3 file playback functionality be achieved in Python?
Python itself does not directly support playing mp3 files, but you can use third-party libraries to achieve the functionality. The most commonly used libraries for this purpose are pygame and pydub.
Utilizing the pygame library:
import pygame
def play_music(file_path):
pygame.init()
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
file_path = "path/to/your/mp3/file.mp3"
play_music(file_path)
Using the pydub library:
from pydub import AudioSegment
from pydub.playback import play
def play_music(file_path):
song = AudioSegment.from_file(file_path, format="mp3")
play(song)
file_path = "path/to/your/mp3/file.mp3"
play_music(file_path)
The above code demonstrates how to use the pygame and pydub libraries to play an mp3 file. Remember to install the necessary libraries and replace file_path with your mp3 file’s path.