Python playsound Module

playsound Module in Python:

We can play sound using the playsound module. This playsound is a cross-platform module for playing audio files.

The single function in the playsound module is the playsound() function. It has only one function.

This module has been tested to play .wav and .mp3 files only and is available for both Python 2 and Python 3.

Syntax:

playsound(path, block)

Parameters:

path: This is required. It is the path to the sound file we want to play. It could be a local file or a URL.

block: This is optional. It is set to True by default. If we set it to False, the function will run asynchronously.

Before we work with this module we use should first install it on our system as shown below.

Installation:

pip install playsound
Output:
Collecting playsound
Downloading playsound-1.3.0.tar.gz (7.7 kB)
Building wheels for collected packages: playsound
Building wheel for playsound (setup.py) ... done
Created wheel for playsound: filename=playsound-1.3.0-py3-none-any.whl size=7035 
sha256=4e4b206f1c64dd86e591df5decf7285c23048d33f4e8c291dd8f63d7226fe91f
Stored in directory: /root/.cache/pip/wheels/ba/f8/bb/ea57c0146b664dca3a0ada4199
b0ecb5f9dfcb7b7e22b65ba2
Successfully built playsound
Installing collected packages: playsound
Successfully installed playsound-1.3.0

playsound Module  in Python

1)For .mp3 File

Approach:

  • Import playsound from playsound module using the import keyword
  • Pass some random .mp3 file path/location to the playsound() function to play the sound of the given .mp3 file.
  • Print some random text for acknowledgment.
  • The Exit of the Program.

Below is the implementation:

# Import playsound from playsound module using the import keyword
from playsound import playsound
# Pass some random .mp3 file path/location to the playsound() function to play the 
# sound of the given .mp3 file
playsound("demofile.mp3")
# Print some random text for acknowledgment
print("The .mp3 file music is playing!!!!")

Output:

The .mp3 file music is playing!!!!

2)For .wav File

Approach:

  • Import playsound from playsound module using the import keyword
  • Pass some random .wav file path/location to the playsound() function to play the sound of given .wav file
  • Print some random text for acknowledgment.
  • The Exit of the Program.

Below is the implementation:

# Import playsound from playsound module using the import keyword
from playsound import playsound
# Pass some random .wav file path/location to the playsound() function to play the 
# sound of given .wav file
playsound("samplefile.wav")
# Print some random text for acknowledgment
print("The .wav file music is playing!!!!")

Output:

The .wav file music is playing!!!!