官术网_书友最值得收藏!

Initializing pygame

The pygame module is a set of highly portable modules that runs on most operating systems. We will use the mixer module from pygame to play the sound files.

Assuming that you have installed the package, let's begin by importing pygame (see code 3.06.py):

import pygame

According to the official API documentation of the mixer module at http://www.pygame.org/docs/ref/mixer.html, we need to initialize pygame before we can play back the audio files.

We initialize pygame in a new method called init_pygame (see code 3.06.py):

def init_pygame(self):
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.init()

The mixer.pre_init method is a special requirement for our drum machine because the lack of it causes a lot of sound lagging. We will not get into the details of audio programming here, but suffice to say that the arguments to the pre_init method are as follows:

pre_init(frequency=22050, size=-16, channels=2, buffersize=512) 

After pygame is initialized like this, the documentation suggests the following code to play the sound. Let's add this to our code as well (see code 3.06.py):

 def play_sound(self, sound_filename):
if sound_filename is not None:
pygame.mixer.Sound(sound_filename).play()
主站蜘蛛池模板: 江都市| 台山市| 乌鲁木齐县| 临漳县| 本溪市| 连山| 苍梧县| 平谷区| 仁寿县| 北辰区| 象州县| 东港市| 鄢陵县| 新和县| 桐乡市| 汨罗市| 唐山市| 纳雍县| 霍邱县| 宁强县| 清徐县| 葫芦岛市| 柳河县| 德化县| 新田县| 尼玛县| 两当县| 伊宁市| 绥江县| 贵州省| 新蔡县| 长宁区| 上虞市| 常熟市| 琼中| 杂多县| 原平市| 濮阳市| 修水县| 扎赉特旗| 四平市|