Trang chủ » blog » 3.22: Playing Sounds

3.22: Playing Sounds

Playing sounds that are stored in sound files is even simpler than displaying images from prototype files. First, you must create a pygame.mixer.Sound object ( which we will call Sound objects for short ) by calling the pygame.mixer.Sound() builder officiate. It takes one string parameter, which is the filename of the sound file. Pygame can load WAV, MP3, or OGG files. The difference between these audio file formats is explained at hypertext transfer protocol : //invpy.com/formats .
To play this sound, call the Sound object ’ south play() method. If you want to immediately stop the Sound object from playing call the stop() method acting. The stop() method acting has no arguments. hera is some sample code :

soundObj = pygame.mixer.Sound('beeps.wav')
soundObj.play()
import time
time.sleep(1) # wait and let the sound play for 1 second
soundObj.stop() 

You can download the beeps.wav file from invpy.com/beeps.wav .
The program execution continues immediately after play() is called ; it does not wait for the audio to finish play before moving on to the following line of code.

The Sound objects are good for sound effects to play when the player takes price, slashes a sword, or collects a coin. But your games might besides be better if they had background music playing regardless of what was going on in the game. Pygame can alone load one music file to play in the background at a time. To load a background music file, call the pygame.mixer.music.load() function and crack it a string argument of the sound file to load. This file can be WAV, MP3, or MIDI format.

Read more: Gem Earning Tips

To begin playing the load sound file as the backdrop music, call the pygame.mixer.music.play(-1, 0.0) function. The -1 argument makes the background music constantly loop when it reaches the end of the sound charge. If you set it to an integer 0 or larger, then the music will only loop that act of times alternatively of looping everlastingly. The 0.0 means to start playing the sound file from the get down. If you pass a larger integer or float, the music will begin playing that many seconds into the reasoned charge. For exemplar, if you pass 13.5 for the second parameter, the sound charge with begin playing at the point 13.5 seconds in from the beginning .
To stop playing the background music immediately, call the pygame.mixer.music.stop() function. This officiate has no arguments .
here is some case code of the sound methods and functions :

# Loading and playing a sound effect:
soundObj = pygame.mixer.Sound('beepingsound.wav')
soundObj.play()

# Loading and playing background music:
pygame.mixer.music.load(backgroundmusic.mp3')
pygame.mixer.music.play(-1, 0.0)
# ...some more of your code goes here...
pygame.mixer.music.stop() 
source : https://leowiki.com
Category : Economy

Post navigation

Leave a Comment

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *