ch09-pag203

IN THIS ADVENTURE, you’ll learn how to use sounds and music with Python and PyGame. PyGame makes sounds and music available, including a whole load of useful functions that make it straightforward to add them to your program.

You’ll make a loop that plays sounds, sounds that play when you press the keys on the keyboard and a basic music player. On top of this, you’ll improve the sprite walking program that you made in Adventure 8 by adding music and sounds to it.

Before you start, you’ll need to download the sample sounds and music needed for this adventure. You can find out how to do this in the Appendix. Make sure you save the files in the Adventure 9 folder.

Let’s get going.

Playing Sounds

In this first program, you’ll learn how to play sounds. The program you make here will form the basis of other programs that you create in the adventure. Sounds are very important in games. They’re an excellent way of sharing information with users and setting tone, all with just some noises. For example, in many video games you can often hear certain enemies sneaking up on you or you can tell if you managed to hit an object with your sword based on the sound it makes.

The program is very straightforward (see Figure 9-1); all it does is play a single sound before closing.

image

FIGURE 9-1 The completed code. Sadly, I can’t take a screen print of the noise it makes!

  1. Open IDLE and create a new file by clicking File⇒New Window.
  2. Save the program as play.py in the Adventure 9 folder.
  3. Next add these lines of code so that the program can use PyGame:

    import pygame
    pygame.init()

  4. The next bit of code will load the sound and play it. The sound in this program is called hit.wav, which is the name of the sound file. Add it to your program now:

    sound = pygame.mixer.Sound('hit.wav')
    sound.play()

  5. If the program finished here it would close before the sound had the chance to play in full, so you need to include a statement to keep the program open for the duration of the sound. Include it in your program now:

    pygame.time.wait(int(sound.get_length()) * 1000)

  6. Save the program and run it with Run⇒Run Module.
  7. When the program runs, it will play the sound but no PyGame window will open—this isn’t needed for the sound to play.

Creating a Noise Loop

In PyGame, you can load several sounds at once. In this program (see Figure 9-2), you’ll create a loop that plays sounds. Every fourth time the loop repeats it will play a different sound. By adapting the program, you can make music or drum loops.

image

FIGURE 9-2 Running this program will play a loop of sounds. Every fourth sound will be different from the other three.

  1. Open IDLE and create a new file with File⇒New Window.
  2. Save the program as noiseLoop.py in the Adventure 9 folder.
  3. First add these two statements to allow the program to use PyGame:

    import pygame
    pygame.init()

  4. The next statement creates the clock. Although the program doesn’t use a window or animations, it still uses the clock. The clock will determine how fast the sounds play later in the program. Add this to your program:

    clock = pygame.time.Clock()

  5. You’re going to use two sounds in this program, crash.wav and hit.wav. The program now needs to load these sounds:

    crash = pygame.mixer.Sound('crash.wav')
    hit = pygame.mixer.Sound('hit.wav')

  6. The next part of the program creates the count and the loop. The loop limits the number of times it repeats so that it only plays 200 sounds before closing:

    count = 0
    while count < 200:

  7. As the loop repeats, the crash sound will play every fourth repeat in the loop. The next bit of code controls this:

        if count % 4 == 0:
            crash.play()

  8. The hit sound will play whenever the crash sound doesn’t play—in other words, three times every loop:

        else:
            hit.play()

  9. The last lines of the code increase the count every time the loop repeats and limit the speed that the loop repeats. In this case, it will repeat twice a second:

        count += 1
        clock.tick(2)

  10. Save the program and run it using Run⇒Run Module.
  11. When the program starts running it plays the sounds in a loop. What does it sound like? Every fourth sound should be a crash, and the other three should be hit sounds.

Making Keyboard Sound Effects

In this program, you’ll use the keyboard to control sounds (see Figure 9-3). When you press the a or s key, it will play a sound. You can add your own sounds and keys by extending the program.

image

FIGURE 9-3 Pressing the a and s keys will now play sounds.

Adding sounds when keys are pressed is used in many video games. For example, in fantasy adventure games characters make a noise when they swing their sword, fire their bow or cast a spell.

  1. Open IDLE and create a new file with File⇒New Window.
  2. Save the program as keyboardSounds.py in the Adventure 9 folder.
  3. Add the first two lines to the program that allow it to use PyGame in the program:

    import pygame
    pygame.init()

  4. This program uses a window, as it also uses the keyboard, so set up the window now with this code:

    windowSize = [400, 300]
    pygame.display.set_mode(windowSize)

  5. Now you’re ready to load the sounds:

    hit = pygame.mixer.Sound("hit.wav")
    crash = pygame.mixer.Sound("crash.wav")

  6. This code starts the game loop:

    done = False
    while not done:

  7. The next bit of code checks if keys are pressed and plays the sounds if they are:

        keys = pygame.key.get_pressed()

        if keys[pygame.K_a]:
            hit.play()

        if keys[pygame.K_s]:
            crash.play()

  8. Now add the code to manage the closing of the window:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
    pygame.quit()

  9. Save the program and run it using Run⇒Run Module.
  10. When the window opens, click on it and press the a and s keys. You should hear the hit and crash sounds. Have some fun with that, but watch out—if you press the keys really quickly, sometimes the sound won’t play.

Using Music with Python

You’re now going to learn how to use music with PyGame and Python. PyGame’s music features work slightly differently than its sound features, and some of the functions vary slightly from the sound functions. Also, only one music file can be loaded at a time, unlike sounds, which can have several loaded at once.

Games use music really well to help set the mood and feel of the game. For example, in mystery games, tense and dramatic music is used to build suspense. Fantasy games often use music that features older, folk instruments and avoid modern music. You’ll create a program that plays a single music file, a file that adds a wobbling volume effect to the sound and a GUI that can control the volume of the music and pause it.

Playing Music

This first program will get you used to using music with PyGame and Python (see Figure 9-4). It will play a single music file. Like the sound programs you created earlier, it won’t open a window when the program runs.

image

FIGURE 9-4 The code to play music in PyGame

  1. Open IDLE and create a new file with File⇒New Window.
  2. Save the program as music.py in the Adventure 9 folder.
  3. First you need to add the two statements that allow the program to use PyGame:

    import pygame
    pygame.init()

  4. The next part of the program loads the music and plays it:

    pygame.mixer.music.load("music.mp3")
    pygame.mixer.music.play()

  5. Just like playing the sounds earlier, the program will close instantly before the music plays unless you add some code to keep it open. This next piece of code uses a loop to make the program stay open while the music is playing:

    while pygame.mixer.music.get_busy():
        pygame.time.wait(200)

  6. Save the program and run it using Run⇒Run Module.
  7. When the program starts, it will play the music once and then close.

Adding Volume Tremolo

Next, you’re going to add tremolo to some music (see Figure 9-5).

image

FIGURE 9-5 When the music plays, the volume goes up and down in a wave.

Tremolo has many uses in music. If the speed of the effect is really fast, it sounds choppy. Effects like this have some use in computer games. Tremolos can be used to make things sound spooky or exciting, depending on the speed.

  1. Open IDLE and create a new Python program with File⇒New Window.
  2. Save the program as tremolo.py in the Adventure 9 folder.
  3. Click in the file editor and add this code to allow your program to use PyGame and the math module. The math module is used later in the program to add the tremolo wobble to the music:

    import math
    import pygame
    pygame.init()

  4. The next part of the program loads and plays the music:

    pygame.mixer.music.load("music.mp3")
    pygame.mixer.music.play()

  5. This part of the program starts the loop that applies the tremolo wobble to the music. The count isn’t used to control the number of times the loop repeats, but instead is used to set the level of the volume in the tremolo:

    count = 0
    while pygame.mixer.music.get_busy():

  6. Inside the loop, the volume level is determined using the first statement in this code. The sin() function creates the wave used to set the volume and the abs() function makes sure the value is positive:

        volume = abs(math.sin(count))

  7. Next, the volume is set and there is a delay before the next loop starts:

    pygame.mixer.music.set_volume(volume)
        count += 0.2
        pygame.time.delay(200)

  8. Save the program and run it using Run⇒Run Module.
  9. When the program starts the music will play, with the volume increasing and decreasing in a wave.

Making a Music Player

Now for something really exciting. In this next program you’ll use Tkinter and PyGame together to make a music player (see Figure 9-6). Your program will create a GUI that allows you to play and pause a song using a button and control its volume with a slider.

image

FIGURE 9-6 The code for a superb basic music player, complete with control button and volume slider, which plays a single song on a loop.

  1. Start as usual by opening IDLE and creating a new file with File⇒New Window.
  2. Save the program as musicPlayer.py in the Adventure 9 folder.
  3. The first part of the program allows it to use PyGame and Tkinter. This code is no different to the code you’d use for PyGame or Tkinter individually:

    import pygame
    import Tkinter as tk
    window = tk.Tk()
    pygame.init()

  4. Next up, add this statement to the program to load the music file:

    pygame.mixer.music.load("music.mp3")

  5. The next two variables are used later in the program to check whether the music has started playing and whether the music is paused. As the music hasn’t started at this point in the program, both of the variables are set to False:

    started = False
    playing = False

  6. So that the button in the program can run code when it is clicked, this program includes these functions to check if the music has started, is playing or has been paused, then plays or pauses the music. The first part of the program makes the playing and started variables global so that the function can change their values:

    def buttonClick():
        global playing, started

  7. The next part of the function checks if the music is not playing. This means that the music is either paused or hasn’t started playing yet:

        if not playing:

  8. In the next bit of code, if the music hasn’t started playing yet (in other words, the Play button hasn’t been clicked yet), the program will start to play the music:

            if not started:
                pygame.mixer.music.play(-1)
                started = True

  9. If the music has started playing but isn’t currently playing, the music must therefore be paused. This code will un-pause the music:

            else:
                pygame.mixer.music.unpause()

  10. When the music is paused, this piece of code changes the text on the button to Pause:

            button.config(text="Pause")

  11. If the music is playing, the next piece of code changes the button’s text to Play and pauses the music when the button is next pressed:

        else:
            pygame.mixer.music.pause()
            button.config(text="Play")

  12. The next bit of code either stops or starts the music, depending on if it was or wasn’t playing already. If it was True (it was playing), it will be swapped to False (stops playing) and vice versa.

    playing = not playing

  13. The next function changes the volume when the slider updates. You’re going to create a volume slider in the next step, which returns a number between 0 and 100—but the volume_set() function requires a number between 0 and 1. For that reason, the last statement in this function divides the slider’s value by 100 so that it is the right size:

    def setVolume(val):
        volume = float(slider.get())
        pygame.mixer.music.set_volume(volume / 100)

  14. Next, you need to create the button and the slider for the program. For this, a Tkinter button and a Tkinter scale object are used. While it’s possible to make these things in PyGame, they have already been built into Tkinter to make it much quicker and easier for you to use them:

    slider = tk.Scale(window, from_=100, to=0, command=setVolume)
    button = tk.Button(window, text="Play", command=buttonClick)

  15. Finally, this piece of code adds the slider and button to the window and starts the Tkinter main loop:

    slider.pack()
    slider.set(100)
    button.pack()
    window.mainloop()

  16. Save the program and run it using Run⇒Run Module.
  17. It’s time to test your handiwork! Click the buttons to play and pause the music and change the volume with the slider.

Adding Sounds and Music to a Game

In Adventure 8, you created a very basic game where a sprite walks around the window. With a few slight changes to the program, you can add music and sounds, which will add sophistication and polish to your game.

In this program, you’ll modify the sprite walking program to add background music and a sound effect when the sprite teleports.

  1. Open the game that you created in Adventure 8. You should have saved it as walkingSprite.py.
  2. When the file opens, find this statement:

    white = pygame.color.Color("#FFFFFF")

  3. Directly below that statement, add the following code to load and play the music and to load the sound when the sprite teleports:

    pygame.mixer.music.load("music.mp3")
    pygame.mixer.music.play(-1)
    teleportSound = pygame.mixer.Sound("teleport.wav")

  4. Next, find these lines of code that teleport the player to a new location:

            if count < 5:
                image = teleport1
            elif count < 10:
                image = teleport2

  5. Directly above that code, add this to play the teleport sound. You use the if statement so that the sound only plays once at the start of the loop:

            if count == 0:
                teleportSound.play()
            else:
                x = random.randrange(0, windowSize[0])
                y = random.randrange(0, windowSize[1])
                count = -1
                locked = False
            count += 1

  6. Save the program and run it using Run⇒Run Module.
  7. When the program starts, the background music will begin playing on a loop.
  8. In the game, press the space bar to teleport the player. Magic! The teleport will make a sound.You can see the completed game in Figure 9-7.
image

FIGURE 9-7 The sprite program now features sounds and music.

Python Command Quick Reference Table

Command

Description

sound = pygame.mixer.Sound(file)

This function is used to load a sound. The filename of the sound is used as an argument. Once the file is loaded, it can be stored in a variable.

sound.play()

To play a sound that has been loaded using the load() function, the play() function is used.

pygame.time.delay()

Instead of you having to import the time module to use with PyGame, PyGame has inbuilt functions that do the same things. This function will make the program wait for a number of milliseconds. The time to wait is given as an argument. There are 1000 milliseconds in 1 second.

sound.get_length()

This function returns the length of a sound in seconds. By dividing it by 1000, you can convert it to milliseconds.

Modulo %

The modulo operator divides one number by another and returns the remainder from the division.

pygame.mixer.music.load()

In PyGame, the load() function is used to load music into the program. The filename is used as an argument to state which sound file will be loaded. Only one music file can be loaded at a time.

pygame.mixer.music.play()

This function is used to play a loaded music file. If you use -1 as an argument, the music will repeat forever.

pygame.mixer.music.get_busy()

When music is playing, this function will return True, and when no music is playing, it will return False.

abs()

The abs() function makes a negative number positive.

pygame.mixer.music.set_volume()

This function is used to set the volume of the PyGame music. The argument should be between 0.0 and 1.0.

image

Achievement Unlocked: Skilled manipulator of sound and music in Python and PyGame programs.

Next Adventure

Hooray! You’ve learned how to use sounds and music with PyGame and Python. You’ve created some cool programs and have learned some tools to help you create programs that use sound.

In the next and final adventure, you’ll make a game by incorporating many of the tips and tricks you’ve learned throughout the adventures in this book!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.47.169