Table of contents
1.
Introduction
2.
Playing audio files in pygame
2.1.
Output: 
3.
Frequently Asked Questions
3.1.
Will pygame play mp3 records?
3.2.
Does pygame blender support mp3?
3.3.
How can I say whether music is playing in Pygame?
3.4.
How would I play a WAV record in Python?
3.5.
What is a pygame blender?
4.
Conclusion
Last Updated: Mar 27, 2024

Playing audio files in pygame

Author Adya Tiwari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Sounds generally come in two significant structures: "encompassing" clam or after-effects of player activities. With PyGame, you get two decisions: Music or Sounds. Music will simply play behind the scenes, and sounds will play whenever you call them to play. We will cover both here by adding them both to our ongoing game. To begin with, we will involve a straightforward tune from YouTube as our game's music, and afterward, we'll add a "crash" sound that we will play, assuming we hit any of the blocks.

Playing audio files in pygame

Game writing computer programs is hugely remunerating these days, and it can likewise be utilized in promoting and as a showing apparatus as well. Game advancement incorporates science, rationale, physical science, AI, and considerably more, and it tends to be incredibly fun. In python, game writing computer programs is done in pygame, and it is perhaps the best module for doing such.

To play music/sound records in pygame, pygame.mixer is utilized (pygame module for stacking and playing sounds). This module contains classes for stacking Sound items and controlling playback. There are essentially four stages to do as such: 

Starting the mixer

mixer.init()
You can also try this code with Online Python Compiler
Run Code

Loading the song

mixer.music.load("song.mp3")
You can also try this code with Online Python Compiler
Run Code

Setting the volume

mixer.music.set_volume(0.7)
You can also try this code with Online Python Compiler
Run Code

Start playing the song

mixer.music.play()
You can also try this code with Online Python Compiler
Run Code

To begin, we should utter a sound:

crash_sound = pygame.mixer.Sound("crash.wav")
You can also try this code with Online Python Compiler
Run Code

The above will allocate the crash.wav sound document to play when we call crash_sound inside PyGame's sound playing usefulness. Notice the document is .wav. PyGame can deal with .mp3 also, yet it is pretty buggy and will work here and there, and at different times it won't. For the most secure bet, go with .wav.

Since it has become so obvious how to call sounds, how might we make music?

pygame.mixer.music.load('jazz.wav')
pygame.mixer.music.play(-1)
You can also try this code with Online Python Compiler
Run Code

The above code will play the music document endlessly (however, you can call it to stop). The - 1 signs PyGame to simply play perpetually, yet, on the off chance that you put a 5 in there, the music would play once and five additional times.

Presently, we believe that the music should play, and then, at that point, we want the accident sound to play when crashes. Additionally, we might want to stop the music if so.

Along these lines, inside our accident work:

def crash():
    ####################################
    pygame.mixer.Sound.play(crash_sound)
    pygame.mixer.music.stop()
    ####################################
    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("You Crashed", largeText)
You can also try this code with Online Python Compiler
Run Code

Above, we're calling PyGame to play the crash_sound, as well as to stop the music. This implies the music will begin once more, assuming the game is re-played.

Presently, the other thing we might believe we should do is figure out how to stop/unpause music when the player controls the game. This is sufficiently simple.

In our stopped capacity:

def paused():
    ############
    pygame.mixer.music.pause()
    #############


And afterward, obviously, we should unpause it:
def unpause():
    global pause
    #################
    pygame.mixer.music.unpause()
    #################
    pause = False
Full Code implementation
from pygame import mixer

# Starting the mixer
mixer.init()

# Loading the song
mixer.music.load("song.mp3")

# Setting the volume
mixer.music.set_volume(0.7)

# Start playing the song
mixer.music.play()

# infinite loop
while True:
   
    print("Press 'p' to pause, 'r' to resume")
    print("Press 'e' to exit the program")
    query = input(" ")
   
    if query == 'p':

        # Pausing the music
        mixer.music.pause()
    elif query == 'r':

        # Resuming the music
        mixer.music.unpause()
    elif query == 'e':

        # Stop the mixer
        mixer.music.stop()
        break
You can also try this code with Online Python Compiler
Run Code

Output: 

The distinction between the music playback and normal Sound playback is that the music is streamed and never really stacked simultaneously—the blender framework just backings a solitary music stream without a moment's delay.

On more seasoned pygame adaptations, MP3 support was restricted under Mac and Linux. This changed in pygame v2.0.2, which got further developed MP3 support. Consider utilizing OGG document design for music as that can give somewhat preferred pressure over MP3 by and large.

Frequently Asked Questions

Will pygame play mp3 records?

Pygame can stack WAV, MP3, or OGG documents. The contrast between these sound document designs is made sense at http://invpy.com/designs. Call the Sound article's play() technique to play this sound. To promptly prevent the Sound article from playing, call the stop() technique.

Does pygame blender support mp3?

The blender framework just backings a solitary music stream on the double. If you have any desire to play an mp3 document, you want to instate the module. Load the paper with pygame. Blender.

How can I say whether music is playing in Pygame?

The worth will be somewhere in the range of 0.0 and 1.0. Returns True when the music stream is effectively playing. Whenever the music is inactive, this profits False in pygame 2.0.

How would I play a WAV record in Python?

NumPy and sound files should be introduced to open WAV documents as NumPy exhibits to play WAV records.

What is a pygame blender?

Blender pygame module for stacking and playing sounds is accessible and instated before utilizing it. The blender module has a set number of channels for the playback of sounds.

Conclusion

Sounds commonly come in two significant structures: "encompassing" clamor or aftereffects of player activities. With PyGame, you get two decisions: Music or Sounds. Music will simply play behind the scenes when you call it too, and sounds will play whenever you call them to play. To play music/sound documents in pygame, a pygame.mixer (pygame module for stacking and playing sounds). This module contains classes for stacking Sound items and controlling playback.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in PythonCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass