How to play music in Python?

playsound module

Hello fellow learner! Today we are going to learn how to play music in Python using a few simple lines of code.

Method 1: The playsound module

The playsound library is a cross platform module that can play audio files. This doesn’t have any dependencies, simply install the library using the pip command and you are ready to go!

To play the music we just have to use the playsound function and pass the music file path as a parameter. The library works for both mp3 and wav files.

The code for the same is shown below:

from playsound import playsound
playsound('Music1.mp3')

The music is played once in the background and then the program is ready for the next part of code to be executed.

Method 2: The pydub Library

The pydub library works only with .wav file format. By using this library we can play, split, merge, edit our .wav audio files.

For the library to work we import two functions namely AudioSegment and play module from playdub.playback module.

Then we simply load the song in .wav format and play the song. The code for the same is shown below:

from pydub import AudioSegment
from pydub.playback import play

song = AudioSegment.from_wav('Music1.wav')
play(song)

Method 3: Using the snack sound kit

The snack sound kit can be used to play audio files in almost all the formats inclusing WAV, AU, AIFF, MP3, CSL, SD, SMP, and NIST/Sphere.

This library needs the GUI module Tkinter in order to play sounds. So we are required to import tkinter module before importing snack sound kit.

Playing audio files through snack sound kit involves creating a Tk window and initialize it. Then sound function is called and read function to load the music.

Finally to play the music we use the play function. The code for the same is shown below:

from Tkinter import *
import tkSnack

wind = Tk()
tkSnack.initializeSnack(wind)

snd = tkSnack.Sound()
snd.read('Music1.wav')
snd.play(blocking=1)

The Output Music

The music below will be the output background music which will be played in each method.

Music Played

Conclusion

Today we learned playing music in python using simple lines of code and various libraries. Awesome!

Try out the codes yourself and play amazing music in Python. Thank you for reading! Happy coding!