Ok so basically I'm working on this pygame game and I'm using the mixer sub module for sounds. However, in pygame if you want to stop a sound, the sound must finish its cycle until it can be stopped. For all my sounds this is ok as they can be a looped 1 second sound. However, I use a falling sound which needs to constantly play in a cycle, but cycling a falling sound that is only 1 second long doesn't sound very effective. So, ultimately I want to know if there is a way to stop a 7 second sound loop instantly without it finishing a cycle.
With PyGame, you get two choices: Music or Sounds. Music will just play in the background when you call it to, and sounds will play at any time you call them to play.
You can use the channel object. Play a specific type of audio in a channel and check to see if the sound is playing.
According to the pygame documentation for pygame.mixer
pygame.mixer.pause()
will temporarily stop playback of all sound channels. You can start them all playing again with;
pygame.mixer.unpause()
For an individual sound, whilst it will stop after a full cycle, you can immediately affect it's volume with;
pygame.mixer.Sound.set_volume(0)
So what I'd try first is stopping the sound at the same time as setting it's volume to zero and seeing if that solves your problem. Alternatively, you can split your mixer into Channels for better controlling sound playback, which will give you the ability to use
pygame.mixer.Channel.pause()
pygame.mixer.Channel.unpause()
On specific groups of sounds rather than all sound. You create a mixer channel with;
pygame.mixer.Channel(id)
You can then play specific sounds on that channel with;
pygame.mixer.Channel.play(Sound, loops=0, maxtime=0, fade_ms=0)
This would also allow you to more dynamically adjust the levels of various types of sounds in your game - for example, environment, music, weather, voices and how they overlap each other, just keep in mind a channel can only play one sound at a time. Because of this, it may by prudent to use;
free_channel = pygame.mixer.find_channel()
free_channel.play(Sound)
or more simply;
pygame.mixer.find_channel().play(Sound)
For everything except your 'falling' channel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With