How to Play Sound in Python

09/11/2021

Contents

In this article, you will learn how to play sound in Python.

Play Sound in Python

In Python, you can play sound using the pygame library, which is a set of Python modules designed for game development. Here are the steps to play sound in Python using pygame:

Install pygame:

Install pygame by running the following command in your terminal or command prompt:

pip install pygame
Import pygame:

Import the pygame library in your Python script by adding the following line at the top of your code:

import pygame
Initialize pygame:

Initialize the pygame library by adding the following code to your script:

pygame.init()
Load the sound file:

Load the sound file that you want to play by adding the following code:

sound = pygame.mixer.Sound("path/to/sound/file.wav")

Replace “path/to/sound/file.wav” with the actual path to your sound file.

Play the sound:

Play the sound by adding the following code:

sound.play()

This will play the sound once.

If you want to play the sound repeatedly, you can use the following code instead:

sound.play(-1)
Stop the sound:

To stop the sound, you can use the following code:

sound.stop()
Quit pygame:

Finally, to quit the pygame library, you can use the following code:

pygame.quit()

Here is an example code that plays a sound file:

import pygame

# Initialize pygame
pygame.init()

# Load the sound file
sound = pygame.mixer.Sound("path/to/sound/file.wav")

# Play the sound once
sound.play()

# Wait for the sound to finish
pygame.time.wait(int(sound.get_length() * 1000))

# Stop the sound
sound.stop()

# Quit pygame
pygame.quit()