concept music in category python

appears as: music, music
Hello World! Third Edition

This is an excerpt from Manning's book Hello World! Third Edition.

In Python, if you want your program to remember something so you can use it later, all you have to do is give that “thing” a name. Python will make a place for that thing in the computer’s memory, whether the thing is a number, some text, a picture, or a piece of music. When you want to refer to that thing again, you just use the same name.

Sound can be both an input and an output. As an input, you’d connect a microphone or other sound source to the computer, and the program would record the sound or do something else with it (maybe send it over the Internet). But sound is much more common as an output, and that’s what we’ll cover in this book. You’ll learn how to play sounds like music or sound effects and add them to your programs, like PyPong.

Adding music to PyPong

There’s just one thing left to do—add the music. We need to load the music file, set the volume, and start it playing. We want it to keep repeating while the game is playing, so we’ll use the special value of -1, like this:

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1)

This code can go anywhere before the main while-loop. That will start the music playing. Now we need to stop the music at the end, and there’s a nice way to do this.

pygame.mixer.music has a method called fadeout() that will fade the music out gradually instead of stopping it abruptly. You just tell it how long the fadeout should be, like this: