Summary: Playing an mp3 audio song using python code sounds interesting. Is it possible to play mp3 in Python? Definitely, that’s what we are going to learn in this tutorial.

There is no inbuilt mechanism available to run a media file (such as mp3) in Python, but there are many 3rd party libraries such as vlc or pygame using which we can play an audio file in Python.

Play mp3 using VLC Python Module

We will use VLC Python module to play an audio file because it is easy and offers many features beyond just play and stop.

So start by installing the vlc.py module using the following command in terminal:

pip install python-vlc

After the installation, we can import the vlc module to play the mp3 file as follows:

  • Import the vlc module.
  • Create a VLC media object by passing the path of the mp3 file to the vlc.MediaPlayer() method as a parameter.
  • Invoke the play() method on the object to play the song.
  • To stop playing use stop() method on the object.

Example: Python Command Line:

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

Example: Python IDE:

import  vlc
import time

p = vlc.MediaPlayer("fade music.mp3")
p.play()
time.sleep(60)
p.stop()

In the python command line, the music will not stop until we execute the next command as p.stop(), whereas in python IDE we will not hear the song playing because the program execution completes in fractions of a second.

Hence to hear the mp3 audio via code written in Python Ide, we have to halt the execution of the program using the time.sleep() method.

Leave a Reply

four × four =