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.

Post author avatar

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.

This Post Has 6 Comments

  1. Wes

    Strange, doesn’t work. Following these instructions, it can’t find the vlc package but has found any other package I’ve installed today.

    1. Vineeta

      you can use pygame for this .

      1. JPhay0001

        Yeah, but if you are making a game, you probably have a background music and the sounds os the game, and págame cant play to files at the same time

  2. Ahmed

    Works just fine

  3. dan

    Same as wes, Can’t find the vlc package

    1. Vineeta

      use pygame

Leave a Reply to dan Cancel reply