In this tutorial let’s learn about How to Play Mp3 File using Python. It sounds interesting to play an mp3 audio music with Python code. There is no built-in mechanism for running a media file (such as mp3) in Python, but there are various third-party libraries available, such as
pygame, that can be used to play an audio file in Python.
Play Mp3 File using the
pygame Package in Python
pygame is a Python language library. It is used to create 2-D games and is a platform on which Python modules may be set up to create a game.
pygame is a collection of modules that allow access to system hardware components such as sound, mouse and so on. I
Initially if you don’t have pygame package installed in your system, then run the below command to get it installed.
pip install pygame
The code snippet is given below.
import pygame pygame.mixer.init() pygame.mixer.music.load('file_name.mp3') pygame.mixer.music.play()
Play Mp3 Files using the
playsound Package in Python
playsound is a cross-platform and single-function module for playing sounds. This module allows you to play a sound file with a single line of code. The
playsound module is a straightforward way to play an mp3 file in Python. It supports both.mp3 and.wav file formats.
Initially if you don’t have
playsound package installed in your system, then run the below command to get it installed.
pip install playsound
In the below code pass the relative path of the mp3 or .wav file basing on your current working directory.
import playsound playsound.playsound('file.mp3')
The above code plays the mp3 file.
Play Mp3 Files using the
vlc Package in Python
The vlc package in python lets you to play any mp3 file using python. The VideoLAN project created the VLC media player, which is a free and open-source portable cross-platform media player software and streaming media server.
We can utilize the VLC media player with Python as well; to install the VLC module in Python, use the code below.
pip install python-vlc
Post installation, we may import the vlc module to play the mp3 file by doing the following:
- Install the vlc module.
- By providing the path to the mp3 file to the vlc, you can create a VLC media object.
- As a parameter, use the MediaPlayer() function.
- To play the song, use the play() method on the object.
- To stop playing, utilize the object’s stop() method.
import vlc song = vlc.MediaPlayer("file.mp3") song.play() #song.stop()
Hope the above code works!
So by using the above packages you can play any mp3 file. There are other modules like
os packages which are also used to play mp3 files. In this article we discussed about the
playsound packages that are used to play mp3 files.
How to Remove Character From String Python
How to Check current Operating System using Python