Saturday, January 24, 2015

Making noise

Having made the sound files, I needed to test everything to make sure that it's working properly. I think this is my first time invoking the pygame module. There are a few new commands that I need:
  • import pygame.mixer: This calls up the pygame mixer module.
  • pygame.mixer.init(48000, -16, 1, 1024): This initializes the mixer. I don't understand all of the parameters really mean. The documentation theoretically explains this to me, but I don't know anything about audio sampling, so it's still nonsense to me.
  • refFileName = pygame.mixer.Sound(fileName): The actual command is the pygame.mixer.Sound() part of this statement. As far as I can tell, this is just making it easier to reference the file in the code.
  • channelName = pygame.mixer.Channel(n): This creates the audio channel for playback. The default number of channels is 8.
  • channelName.play(refFileName): This actually plays the sound.
  • Armed with these commands, I was able to create a fairly basic file that plays through my four tones for the Simon game.
    import pygame.mixer
    import time
    
    pygame.mixer.init(48000, -16, 1, 1024)
    redtone = pygame.mixer.Sound("RedTone.ogg")
    yellowtone = pygame.mixer.Sound("YellowTone.ogg")
    greentone = pygame.mixer.Sound("GreenTone.ogg")
    bluetone = pygame.mixer.Sound("BlueTone.ogg")
    
    redChannel = pygame.mixer.Channel(1)
    yellowChannel = pygame.mixer.Channel(2)
    greenChannel = pygame.mixer.Channel(3)
    blueChannel = pygame.mixer.Channel(4)
    
    redChannel.play(redtone)
    time.sleep(1)
    yellowChannel.play(yellowtone)
    time.sleep(1)
    greenChannel.play(greentone)
    time.sleep(1)
    blueChannel.play(bluetone)
    time.sleep(1)
    
I learned a couple things while playing around with this. First, it's possible to play multiple sounds at the same time on different channels. In fact, playing the four tones at once makes for a very good error sound. So I think I'll incorporate that fortunate discovery into the game. Another thing that I learned is that if the program reaches the end while a sound is play, the sound does not finish playing. It just cuts off. This is why the final time.sleep() command is there. It just ensures that half-second tone completely finishes.

My next task will be to get the sounds to play with the flashing lights. And then I'll start into a graphical presentation of the game using more of the pygame module.

No comments:

Post a Comment