How to Play Mp3 File Using Python
-
Play Mp3 Files With Python Using the
playsound
Package -
Play Mp3 Files With Python Using the
pygame
Package -
Play Mp3 Files With Python Using the
vlc
Package -
Play Mp3 Files With Python Using
webbrowser
Package -
Play Mp3 Files With Python Using the
os
Package
This tutorial explains how we can play mp3 files with Python using packages like pygame
, vlc
, playsound
and webbrowser
.
Play Mp3 Files With Python Using the playsound
Package
One simple way to play an mp3 file using Python is with the help of playsound
library. It can be used to play both .mp3
and .wav
files.
import playsound
playsound.playsound("sample.mp3")
It plays the sample.mp3
file placed in the current working directory. If the .mp3
is placed in any other directory, make sure you pass the path of the mp3 file relative to the current working directory.
If you don’t have the playsound
package installed on your system, you can install it with the command:
pip install playsound
Play Mp3 Files With Python Using the pygame
Package
pygame
is a collection of modules that provide access to hardware components of the system like sound, mouse, keyboard, and so on. We can use this package to play mp3 files in Python.
import pygame
pygame.mixer.init()
pygame.mixer.music.load("sample.mp3")
pygame.mixer.music.play()
This code snippet plays the sample.mp3
file in the current working directory. If you face a problem playing mp3 files using pygame
, you can convert the mp3 file into .wav
format.
If you don’t have pygame
package installed on your system, you can install it with the command.
pip install pygame
Play Mp3 Files With Python Using the vlc
Package
We can also use the vlc
package to play mp3 files in Python.
import vlc
p = vlc.MediaPlayer("sample.mp3")
p.play()
This code snippet plays the sample.mp3
file in the current working directory.
If you don’t have vlc
package installed on your system, you can install it with the command:
pip install python-vlc
Play Mp3 Files With Python Using webbrowser
Package
import webbrowser
webbrowser.open("sample.mp3")
The code snippet will open a tab in browser window and play the sample.mp3
file in the current working directory.
Play Mp3 Files With Python Using the os
Package
We can use music players on our system to play mp3 files through Python. For this purpose, we take help of os
module.
The native media players vary across different operating systems. Hence, the code for one platform might not work on another.
We use the following code snippet for the Linux platform to play mp3 files using the os
package in Python.
import os
os.system("mpg123 " + "sample.mp3")
If you don’t have mpg123
installed on your Linux system, you can install it using the following command:
sudo apt install mpg123
For macOS, we use the following code snippet to play an mp3 file using os
package in Python.
import os
os.system("afplay " + "sample.mp3")
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn