ID : 8
viewed : 264
Tags : PythonPython Audio
92
This tutorial explains how we can play mp3 files with Python using packages like pygame
, vlc
, playsound
and webbrowser
.
playsound
PackageOne 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
pygame
Packagepygame
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
vlc
PackageWe 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
webbrowser
Packageimport 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.
os
PackageWe 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")