Pygame platform game 5: sounds and mixer

In this episode we will talk about sounds. How to add them in pygame? I found that it was a bit laggy, i.e. there was a delay between the pressing of the button to jump and the release of the sound, but I found a little trick that lets you get rid of the latency, fortunately. Here is the code for the sound. Be careful to the order of the statements, it is very important to avoid the issue I just mentioned:

The trick here is to put pre_init before pygame init(). Someone also wrote on stackoverflow that he used to quit() the mixer befor the .init method. I experimented and decided to leave them both as you see above. The frequency rate… I think should be the same (44100 or 22050… maybe you should choose only one type, not like I did, but it does not cause me any problem at the moment… I will change it later on). You can also change the buffer size (512 to 1024…), experiment.

This is just to initialize the sound to play you have to load the sounds like this:

Then, to play them effectively, you gotta place this statements where you want the sound to play:

The soundtrack in background

To load and play a soundtrack continuosly:

The whole code

For the moment we will stop here. In another video I will talk about the other stuff I am changing in the game. This is the code, until now:

The images

These go into imgs folder


The video about sounds in Pygame

Pygame's Platform Game

Other Pygame's posts