Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the skills of sound addition in python pygame games?

Shulou Source: shulou.com Published: 2022-06-03 01:20:20 10月26日 Update

This article introduces the relevant knowledge of "what are the skills for sound addition in python pygame games?". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

Start the mixer process

Second, create a sound directory

Add sound to Pygame

Fourth, trigger a sound

Pygame's mixer module can play one or more sounds according to commands, and can also mix these sounds together.

It takes four steps to get the sound:

Start the mixer process

First, start the mixer process in the settings section of your code.

Pygame.init () pygame.font.init () pygame.mixer.init () # add this line II. Create a sound directory

First create a new directory in your game directory, which can be named sound

S = 'sound'

Add sound to Pygame

Find the sound file and move it to the sound folder in your game directory.

Assuming you have downloaded a sound file called ouch.ogg, in the settings section of your code, create a variable that represents the sound file you want to use:

Ouch = pygame.mixer.Sound (os.path.join (s, 'ouch.ogg')) IV. Trigger a sound

To use a sound, all you have to do is call this variable when you want to trigger it.

For enemy in enemy_hit_list: pygame.mixer.Sound.play (ouch) score-= 1

Attaching: adding background music

If you have music or exciting sound effects that you want to play in the background of your game, you can use the music function in the mixer module in Pygame.

In your settings section, load the music file:

Music = pygame.mixer.music.load (os.path.join (s, 'music.ogg'))

Then, start the music:

Pygame.mixer.music.play (- 1)

The-1 value tells Pygame to infinitely loop the music file. You can set it to any value from 0 to higher to define how many times the music loops before it stops.

This is the end of the content of "what are the skills for sound addition in python pygame games". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Sounds files directories music processes parts skills code content variables more modules knowledge background loops utility excitement learning next between Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Redmi OPPO Reno MySQL Microsoft