Play sound in Python

Play sound in Python

Playing sound in Python can be achieved using various third-party libraries. Here are a few popular methods:

1. playsound module:

This is one of the simplest packages to play sound files.

First, you need to install the module:

pip install playsound 

Usage:

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

2. pygame module:

pygame is a larger library primarily used for game development but can be used to play audio files.

Install pygame:

pip install pygame 

Usage:

import pygame.mixer # Initialize the mixer module pygame.mixer.init() # Load and play the sound pygame.mixer.music.load('path_to_your_audio_file.mp3') pygame.mixer.music.play() # Keep the program running while the music is playing while pygame.mixer.music.get_busy(): pygame.time.Clock().tick(10) 

3. wave and pyaudio:

This is a method to play .wav files:

First, install pyaudio:

pip install pyaudio 

Usage:

import wave import pyaudio # Open the file wf = wave.open('path_to_your_audio_file.wav', 'rb') # Create a PyAudio object p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(1024) while data: stream.write(data) data = wf.readframes(1024) stream.stop_stream() stream.close() p.terminate() 

Remember that each of these methods has its own set of functionalities and capabilities. While playsound is straightforward and easy to use for simply playing sound, libraries like pygame offer more advanced functionalities. Choose the method that best fits your project requirements.


More Tags

ngtools parallel-processing google-signin repeat width executequery apache-tika uicollectionviewlayout text-cursor author

More Programming Guides

Other Guides

More Programming Examples