Playing an mp3 audio song through python code sounds interesting. Is it possible to play mp3 in Python?

Yes, we can easily play an mp3 audio using python. All we need to use the 3rd part library like vlc, pygame, etc because python does not have inbuilt support for mp3 files.

In this article, we will use VLC Python module because it offers many features beyond just play and stop.

Start by installing the module using the following command from the command line.

pip install python-vlc

Once it has been successfully completed writing import vlc in your python program will not throw any error.

So import the vlc module and create the VLC media object by passing the path of the mp3 file to vlc.MediaPlayer() method. Once done play the music using play() method and stop the music using stop() method on the object.

In Python Command Line.

>>>import  vlc
>>>p = vlc.MediaPlayer("fade music.mp3")

In Python Ide

import  vlc
import time

p = vlc.MediaPlayer("fade music.mp3")

In python command line the music will not stop until you execute the next command as p.stop(), whereas in python ide the program execution happens just for the fraction of the seconds therefore you will not hear the song playing.

Hence in Python Ide, you need to use halt the execution of the program using time.sleep() to hear the song until p.stop() gets executed.

I hope now you can easily play an mp3 song in python. If you have any doubts or suggestion then comment below.

Leave a Reply

nine − four =