How to Play Sound in Python
It is an easy task to play sound using Python script, because this language contains many modules to use script in order to to play or record sound. By using these modules, you can play audio files such as mp3, wav, and other audio file types. You must first install the sound module before using the module in the script. This tutorial will show how to install different types of Python modules to play sound.
Play Sound Using playsound
The playsound module is the simplest module to use for playing sound. This module works on both Python 2 and Python 3, and is tested to play wav and mp3 files only. It contains only one method, named playsound(), with one argument for Linux to take the audio filename for playing.
Installation:
Run the following pip3 command to install this module in Python 3:
Example: Playing wav and mp3 Files Using playsound
In the following script, a wav filename will be taken as input first and the file will be played using the playsound() method. Next, an mp3 filename will be input and played via the same method.
# Import playsound module
from playsound import playsound
# Input an existing wav filename
wavFile = input("Enter a wav filename: ")
# Play the wav file
playsound(wavFile)
# Input an existing mp3 filename
mp3File = input("Enter a mp3 filename: ")
# Play the mp3 file
playsound(mp3File)
Output:
If both files exist, then the sound file will start to play.
Play Sound Using pydub
The pydub module supports both Python 2 and Python 3. This module has many useful features other than Python sound modules. The pydub module supports different types of audio files. This module can be used to divide segments of any audio file or append segments to the audio files. You can also add a simple effect on top of the sound. This module directly depends on two other modules, called ffmpeg and libavcodec-extra. Before installing the pydub module, you must first install these modules.
Installation:
Run the following commands to install the pydub package of Python:
$ pip3 install pydub
Example-1: Play Local wav and mp3 Files
This module uses the form_file() method for playing wav file and form_mp3() method for playing an mp3 file. The play() method is used here to play the wav and mp3 file:
from pydub import AudioSegment
from pydub.playback import play
# Input an existing wav filename
wavFile = input("Enter a wav filename: ")
# load the file into pydub
sound = AudioSegment.from_file(wavFile)
print("Playing wav file...")
# play the file
play(sound)
# Input an existing mp3 filename
mp3File = input("Enter a mp3 filename: ")
# load the file into pydub
music = AudioSegment.from_mp3(mp3File)
print("Playing mp3 file...")
# play the file
play(music)
Output:
If both wav and mp3 filenames exist, then the sound will play, and the following output will appear:
Example-2: Download and Play wav and mp3 Files from URL
The following example shows how any wav or mp3 file can be played after downloading the file from a valid URL location. The urllib module is used in the script to download the sound file.
# Import necessary modules
from pydub import AudioSegment
from pydub.playback import play
import urllib
# Set the wav filename
filename = "service-bell.wav"
# Download the wav file from url
print("downloading wav file....")
urllib.request.urlretrieve("https://ift.tt/3cAhhtV", filename)
# load the file into pydub
sound = AudioSegment.from_file(filename)
print("Playing wav file...")
# play the file
play(sound)
# Set the mp3 filename
filename = "birds.mp3"
# Download an mp3 file
print("downloading mp3 file....")
urllib.request.urlretrieve("https://ift.tt/2zJCNhi", filename)
# load the file into pydub
birdsound = AudioSegment.from_mp3(filename)
print("Playing mp3 file...")
# Play the result
play(birdsound)
print("Finished.")
Output:
The sound file will start to play after completing the download, and the following output will appear:
Play sound using tksnack
The tksnack module depends on another module, named tkinter, to activate a tk object in the script. tksnack commands can be used after initializing the tk object. You must install both tkinker and tksnack packages for Python 3.
Installation:
$ sudo apt-get install python3-tksnack
Example: Play wav File Using tksnack
In the following script, the tkSnack module is initialized by using the tkinter object, and the next play() method is used to play the wav file. Here, the blocking argument specifies that the sound will play asynchronously.
# Import necessasry modules
import tkinter
import tkSnack
import os
# Initialize tk object to use tksnack
root = tkinter.Tk()
tkSnack.initializeSnack(root)
#Define tksnack object
sound = tkSnack.Sound()
# Input an existing wav filename
wavFile = input("Enter a wav filename: ")
if os.path.exists(wavFile):
# Read the file
sound.read(wavFile)
# Play sound
sound.play(blocking=1)
else:
# Print the message if the file path does not exist
print ("Wav file does not exist.")
Output:
The sound will start to play if the wav file exists, and the following output will appear:
Play Sound Using simpleaudio
The simpleaudio module is a package of Python 3 that can play audio sounds. This module is mainly designed to play wav files and NumPy arrays. You will need to install the package before using this module. This sound package directly depends on another package called libasound2-dev. You will need to install the libasound2-dev package first, and after that, you can install the simpleaudio package.
Installation:
Run the following command to install the packages:
$ pip3 install simpleaudio
Example: Play wav File Using simpleaudio
In the following script, any wav filename will be taken as the input. If the file exists, then the script will play the sound file; otherwise, the script will display an error message.
# Import simpleaudio sound module
import simpleaudio as sa
# Input an existing wav file name
wavFile = input("Enter a wav filename: ")
# Play the sound if the wav file exists
try:
# Define object to play
w_object = sa.WaveObject.from_wave_file(wavFile)
# Define object to control the play
p_object = w_object.play()
print("Sound is playing...")
p_object.wait_done()
print("Finished.")
# Print error message if the file does not exist
except FileNotFoundError:
print("Wav File does not exists")
Output:
The sound file will play, and the following output will appear after playing the sound:
Conclusion
The basic uses of four Python modules to play sound are explained in this tutorial by using a number of examples. The sound playing task is shown in this tutorial only, but you can record, edit, and different sound-related tasks by using Python script.
from Linux Hint https://ift.tt/2Z7qAh1
0 Comments