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 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")

Example: Python IDE:

import  vlc
import time

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

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.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply