• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mixer.pre_init函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pygame.mixer.pre_init函数的典型用法代码示例。如果您正苦于以下问题:Python pre_init函数的具体用法?Python pre_init怎么用?Python pre_init使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了pre_init函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: prepare

def prepare():
    """ Initialise sound module. """
    audio.plugin_dict['pygame'] = AudioPygame
    if pygame:
        # must be called before pygame.init()
        if mixer:
            mixer.pre_init(sample_rate, -mixer_bits, channels=1, buffer=1024) #4096
开发者ID:nestormh,项目名称:pcbasic,代码行数:7,代码来源:audio_pygame.py


示例2: todo_test_pre_init__keyword_args

    def todo_test_pre_init__keyword_args(self):
        # Fails on Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
##        configs = ( {'frequency' : f, 'size' : s, 'channels': c }
##                    for f in FREQUENCIES
##                    for s in SIZES
##                    for c in CHANNELS )
        configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]

        for kw_conf in configs:
            mixer.pre_init(**kw_conf)
            mixer.init()

            mixer_conf = mixer.get_init()
            
            self.assertEquals(
                # Not all "sizes" are supported on all systems.
                (mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
                (kw_conf['frequency'],
                 abs(kw_conf['size']),
                 kw_conf['channels'])
            )
            
            mixer.quit()
开发者ID:IuryAlves,项目名称:pygame,代码行数:25,代码来源:mixer_test.py


示例3: init

def init():
    """ Must be called before pygame.init() to enable low latency sound
    """
    # reduce sound latency.  the pygame defaults were ok for 2001,
    # but these values are more acceptable for faster computers
    if _pygame:
        mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
开发者ID:Airon90,项目名称:Tuxemon,代码行数:7,代码来源:__init__.py


示例4: main

def main():
    intervals = {'major 2nd': 2,
                 'minor 3rd': 3, 'major 3rd': 4,
                 'perfect 4th': 5,
                 'perfect 5th': 7}
    interval_lookup = {}
    for key, val in intervals.copy().iteritems():
        # We don't want to modify the dict we're iterating though
        interval_lookup[val] = key  # Add the reverse to the dict

    used_tones = [False] * 12
    notes = len(Note.chromatic)
    tune = []

    def prev_interval():
        """Return the most recent interval"""
        previous_interval = (tune[-2] - tune[-1]) % notes
        # interval might not be in intervals
        if previous_interval in interval_lookup:
            previous_interval = interval_lookup[previous_interval]
        return previous_interval

    def get_new_note(pitch, interval=None):
        """This is embedded so we don't need to pass in used_tones.
        Checks that the note is valid otherwise it picks a new note and sets it
        as used"""
        if interval is not None:
            pitch = (pitch + interval) % len(Note.chromatic)
        if used_tones[pitch] is True and False in used_tones:
            pitch = rand_choice([i for i, used in enumerate(used_tones)
                                 if used is False])
        used_tones[pitch] = True
        return pitch


    tune.append(get_new_note(randint(0, notes - 1)))
    tune.append(get_new_note(tune[-1], rand_choice(intervals.values())))

    while False in used_tones:
        # intelligently choose a new pitch based on the interval between the
        # previous two
        note = get_new_note(randint(0, notes - 1))
        if randint(1, 4) > 1:  # 1 in 4 chance for a random note
            if prev_interval() == 'major 3rd':
                # if the previous interval was a minor 3rd, attempt to follow
                # it with a major 2nd
                # mod is used to stay in the octave
                note = get_new_note(tune[-1], intervals['major 2nd'])
            elif prev_interval == 'perfect 4th':
                # if the previous interval was a major 3rd, attempt to follow
                # by going down a minor 3rd
                note = get_new_note(tune[-1], -1* intervals['major 3rd'])

        tune.append(note)

    mixer.pre_init(44100, -16, 1, 1024)
    pygame.init()
    play_tune([Note.chromatic[note] for note in tune])
    pygame.quit()
开发者ID:solarmist,项目名称:python-learning-experiments,代码行数:59,代码来源:tonerow.py


示例5: __init__

 def __init__(self, delegate):
     super(SoundController, self).__init__()
     self.logger = logging.getLogger('game.sound')
     try:
         mixer.pre_init(44100,-16,2,2048)
         mixer.init()
     except Exception, e:
         # The import mixer above may work, but init can still fail if mixer is not fully supported.
         self.enabled = False
         self.logger.error("pygame mixer init failed; sound will be disabled: "+str(e))
开发者ID:CarnyPriest,项目名称:CCCforVP,代码行数:10,代码来源:sound.py


示例6: todo_test_init__zero_values

 def todo_test_init__zero_values(self):
     # Ensure that argument values of 0 are replaced with
     # preset values. No way to check buffer size though.
     mixer.pre_init(44100, 8, 1)  # None default values
     mixer.init(0, 0, 0)
     try:
         self.failUnlessEqual(mixer.get_init(), (44100, 8, 1))
     finally:
         mixer.quit()
         mixer.pre_init(0, 0, 0, 0)
开发者ID:IuryAlves,项目名称:pygame,代码行数:10,代码来源:mixer_test.py


示例7: main

def main():
    mixer.pre_init(44100, -16, 2, 1024) #sound effects are delayed on my windows machine without this, I think the buffer is initialized too large by default
    pygame.init()
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    while True:
        screen =  get_screen()
        pygame.display.set_caption(TITLE)
        pygame.display.set_icon(load_image(os.path.join('blocks', 'lightgreen.png')))
        menu = Menu(screen)
开发者ID:ubuntunux,项目名称:KivyProject,代码行数:11,代码来源:main.py


示例8: init_mixer

def init_mixer():
    """
    Check that the mixer's initialized and initialize it if not.
    
    """
    # Check PyGame is available
    # This will raise an error if it's not
    check_pygame()
    from pygame import init, mixer
    # Set the mixer settings before initializing everything
    mixer.pre_init(frequency=44100)
    init()
开发者ID:johndpope,项目名称:jazzparser,代码行数:12,代码来源:output.py


示例9: __init__

  def __init__(self, music_directory):
    """ Initialize the MusicPlayer with the music in the given directory. 
    Needs to be called before pygame.init().

    """
    self.music_directory = music_directory
    songs = self.get_list_of_songs(self.music_directory)
    if (len(songs) <= 0):
      print("Please place a .wav file in the directory %s" % directory)
    
    # Initialize mixer with correct frame rate
    mixer.pre_init(self.get_frame_rate(music_directory + '/' + songs[0]))    
开发者ID:SheldonSandbekkhaug,项目名称:radio,代码行数:12,代码来源:MusicPlayer.py


示例10: init_sound

def init_sound(experiment):

	print(
		u"openexp.sampler._legacy.init_sound(): sampling freq = %d, buffer size = %d" \
		% (experiment.sound_freq, experiment.sound_buf_size))
	if hasattr(mixer, u'get_init') and mixer.get_init():
		print(
			u'openexp.sampler._legacy.init_sound(): mixer already initialized, closing')
		pygame.mixer.quit()
	mixer.pre_init(experiment.sound_freq, experiment.sound_sample_size, \
		experiment.sound_channels, experiment.sound_buf_size)
	mixer.init()
开发者ID:FieldDB,项目名称:OpenSesame,代码行数:12,代码来源:legacy.py


示例11: init_sound

def init_sound(experiment):

	"""
	Initializes the pygame mixer before the experiment begins.

	Arguments:
	experiment -- An instance of libopensesame.experiment.experiment
	"""

	print "openexp.sampler._legacy.init_sound(): sampling freq = %d, buffer size = %d" \
		% (experiment.sound_freq, experiment.sound_buf_size)
	if hasattr(mixer, 'get_init') and mixer.get_init():
		print 'openexp.sampler._legacy.init_sound(): mixer already initialized, closing'
		pygame.mixer.quit()
	mixer.pre_init(experiment.sound_freq, experiment.sound_sample_size, \
		experiment.sound_channels, experiment.sound_buf_size)	
	mixer.init()
开发者ID:EoinTravers,项目名称:OpenSesame,代码行数:17,代码来源:legacy.py


示例12: __init__

    def __init__(self,game,priority=10):
        super(SoundController, self).__init__(game,priority)
        self.logger = logging.getLogger('game.sound')
        try:
            mixer.pre_init(frequency=22050, size=-16, channels=2, buffer=256)  #256 prev
            mixer.init()
            mixer.set_num_channels(8)

            self.queue=deque() #for queing up quotes

            mixer.set_reserved(CH_MUSIC_1)
            mixer.set_reserved(CH_MUSIC_2)
            mixer.set_reserved(CH_VOICE)

            #mixer.Channel(CH_VOICE).set_endevent(pygame.locals.USEREVENT)  -- pygame event queue really needs display and cause a ton of issues, creating own

        except Exception, e:
            self.logger.error("pygame mixer init failed; sound will be disabled: "+str(e))
            self.enabled = False
开发者ID:mjocean,项目名称:PyProcGameHD-SkeletonGame,代码行数:19,代码来源:sound.py


示例13: __init__

    def __init__(self, volume):
        mixer.pre_init(44100, -16, 2, 1024)
        mixer.init()
        
        self.menuSound = normpath("sounds/theme.mp3")
        self.gameSound = normpath("sounds/gameTheme.mp3")

        self.successSound = mixer.Sound(normpath("sounds/success.wav"))
        self.failureSound = mixer.Sound(normpath("sounds/failure.wav"))
        self.victorySound = mixer.Sound(normpath("sounds/victory.wav"))

        self.currSound = self.menuSound

        
        self.volumeLevel = volume
        self.setVolume(self.volumeLevel)

        
        mixer.music.load(self.menuSound)
开发者ID:hackerj,项目名称:Treasure-Hunting-Game,代码行数:19,代码来源:Sounds.py


示例14: __init__

 def __init__(self):
     try:
         #Inicilializo el modulo para ejecutar sonidos
         if sys.platform.find('win') != -1:
             mixer.pre_init(44100,16,1,4096)
         else:
             mixer.pre_init(44100)
         mixer.init()
         self.__canal = mixer.find_channel()
         self.__cola = []
         self.__ejecutando_sonidos = False
         self.__end_sound_event = False
         self.__new_sound_event = False
         self.__escuchar = True
         self.__sonido_actual = ""
         self.SILENCE_CHANNEL = USEREVENT + 4
         self.nombre_grupo_sonido = ""
     except pygame.error, e:
         raise Exception("ERROR!: " + str(e) + ", al inicilizar el video. La aplicacion se cerrara")
开发者ID:joausaga,项目名称:clubdeothello,代码行数:19,代码来源:audio.py


示例15: __init__

    def __init__(self):
        """Initializes player in this order:
		   External libraries
		   Data attributes
		   Populating data attributes
		"""
        threading.Thread.__init__(self)
        pygame.init()
        mixer.pre_init(44100, -16, 2, 2048)  # frequency, size, channels, buffersize
        mixer.music.set_endevent(SONG_END)

        self.isPaused = False
        self.isStopped = False
        self.isOnDrakeToday = True
        self.Files = []
        self.CurrentPosition = 0

        self.__loadFiles()

        self.TotalFiles = len(self.Files)
开发者ID:johnmarinelli,项目名称:drake-player,代码行数:20,代码来源:player.py


示例16: __init__

 def __init__(self, audio_queue, **kwargs):
     """Initialise sound system."""
     if not pygame:
         raise InitFailed('Module `pygame` not found')
     if not numpy:
         raise InitFailed('Mdoule `numpy` not found')
     if not mixer:
         raise InitFailed('Module `mixer` not found')
     # this must be called before pygame.init() in the video plugin
     mixer.pre_init(
         synthesiser.SAMPLE_RATE, -synthesiser.SAMPLE_BITS, channels=1, buffer=BUFSIZE
     )
     # synthesisers
     self.signal_sources = synthesiser.get_signal_sources()
     # sound generators for each voice
     self.generators = [deque(), deque(), deque(), deque()]
     # do not quit mixer if true
     self._persist = False
     # keep track of quiet time to shut down mixer after a while
     self.quiet_ticks = 0
     AudioPlugin.__init__(self, audio_queue)
开发者ID:robhagemans,项目名称:pcbasic,代码行数:21,代码来源:audio_pygame.py


示例17: __init__

 def __init__(self, audio_queue):
     """Initialise sound system."""
     if not pygame:
         logging.warning('PyGame module not found. Failed to initialise PyGame audio plugin.')
         raise base.InitFailed()
     if not numpy:
         logging.warning('NumPy module not found. Failed to initialise PyGame audio plugin.')
         raise base.InitFailed()
     if not mixer:
         logging.warning('PyGame mixer module not found. Failed to initialise PyGame audio plugin.')
         raise base.InitFailed()
     # this must be called before pygame.init() in the video plugin
     mixer.pre_init(synthesiser.sample_rate, -synthesiser.sample_bits, channels=1, buffer=1024) #4096
     # synthesisers
     self.signal_sources = synthesiser.get_signal_sources()
     # sound generators for each voice
     self.generators = [deque(), deque(), deque(), deque()]
     # do not quit mixer if true
     self._persist = False
     # keep track of quiet time to shut down mixer after a while
     self.quiet_ticks = 0
     base.AudioPlugin.__init__(self, audio_queue)
开发者ID:hongriTianqi,项目名称:pcbasic,代码行数:22,代码来源:audio_pygame.py


示例18: init

def init():
    if os.name == 'posix': # We need to force stereo in many cases.
        try: mixer.pre_init(44100, -16, 2)
        except pygame.error: pass

    pygame.init()
    config.init(rc_file)
    os.chdir(angrydd_path)
    pygame.display.set_caption("Angry, Drunken Programmers")
    try: pygame.display.set_icon(pygame.image.load("angrydd.png"))
    except pygame.error: pass
    pygame.mouse.set_visible(False)
    if config.getboolean("settings", "fullscreen"): flags = FULLSCREEN
    else: flags = 0
    pygame.display.set_mode([800, 600], flags)

    import game
    import menu
    import boxes
    import characters

    boxes.TickBox.sound = load.sound("tick.wav")
    boxes.TickBox.sound.set_volume(0.3)

    boxes.BreakBox.sound = load.sound("break.wav")
    boxes.BreakBox.sound.set_volume(0.3)

    boxes.Special.sound = load.sound("select-confirm.wav")
    boxes.Special.sound.set_volume(0.5)

    game.FallingBoxes.rotate_sound = load.sound("rotate.wav")
    game.FallingBoxes.rotate_sound.set_volume(0.2)

    menu.Menu.bg = load.image("menu-bg.png").convert()

    characters.init()

    mixer.music.load(os.path.join("music", "intro.ogg"))
    mixer.music.play(-1)
开发者ID:joshuacronemeyer,项目名称:Angry-Drunken-Programmers,代码行数:39,代码来源:angrydd.py


示例19: __init__

 def __init__(self):
     mixer.init()
     mixer.pre_init(44100, -16, 2, 1024*4)
开发者ID:rlegendi,项目名称:Taltos,代码行数:3,代码来源:MusicPlayer.py


示例20: run_game

def run_game():
    # Game parameters
    SCREEN_WIDTH, SCREEN_HEIGHT = 400, 400
    BG_COLOR = 150, 150, 80
    CREEP_FILENAMES = [
        'bonehunter2.png', 
        'skorpio.png',
        'tuma.png', 
        'skrals.png',
        'stronius1.png',
        'stronius2.png',
        'metus_with_guards.png']
    TOWER_FILENAMES = [
        'matanui.png',
        'malum.png',
        'gresh.png',
        'gelu.png',
        'vastus.png',
        'kiina.png',
        'ackar.png',
        'straak.png'
        ]
    SELL_FILENAME = 'Sell.png'
    RAIN_OF_FIRE = 'rain_of_fire.png'
    TORNADO = 'tornado.png'
    TORNADO_BIG = 'tornado_big.png'
    BUTTON_FILENAMES = TOWER_FILENAMES + [RAIN_OF_FIRE, TORNADO, SELL_FILENAME]

    money = 643823726935627492742129573207

    mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag
    mixer.init()
    mixer.set_num_channels(30)
    print "mix", mixer.get_num_channels()
    EXPLOSIONS = [mixer.Sound('expl%d.wav'%(i)) for i in range(1, 7)]
    FIRING = [mixer.Sound('fire%d.wav'%(i)) for i in range(1, 4)]
    N_CREEPS = 10
    N_TOWERS = 0

    pygame.init()

    background = pygame.image.load("Background_Level_1.JPG")
    path = pygame.image.load("Path_Level_1.png")
    w, h = background.get_size()
    assert (w, h) == path.get_size()
    sc = min(1024.0/w, 1024.0/h)
    background = pygame.transform.scale(background, (int(w * sc), int(h * sc)))
    path = pygame.transform.scale(path, (int(w * sc), int(h * sc)))
    backgroundRect = background.get_rect()

    starts, paths = create_paths(path)

    screen = pygame.display.set_mode(
        background.get_size(), 0, 32)
    clock = pygame.time.Clock()

    # Create N_CREEPS random creeps.
    creeps = []    
    for i in range(N_CREEPS):
        creeps.append(Creep(screen,
                            choice(CREEP_FILENAMES), 
                            (   choice(starts)[::-1]), # reversed x and y
                            (   choice([-1, 1]), 
                                choice([-1, 1])),
                            0.05,
                            paths,
                            choice(EXPLOSIONS)))

    towers = [Tower(screen,
                    choice(TOWER_FILENAMES),
                    (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])),
                    (1, 1),
                    0.0,
                    paths, radius=100, max_attacks=3, firing_sounds=FIRING) for i in range (N_TOWERS)]

    buttons = [Button(screen,
                      buttonfile,
                      (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])),
                      (1, 1),
                      0.0,
                      paths) for buttonfile in BUTTON_FILENAMES]



    rightedge = screen.get_width() - 5
    for b in buttons[:len(buttons)//2]:
        b.pos = vec2d(rightedge - b.image.get_width() / 2, 5 + b.image.get_height() / 2)
        rightedge -= (b.image.get_width() + 5)
    rightedge = screen.get_width() - 5
    for b in buttons[len(buttons)//2:]:
        b.pos = vec2d(rightedge - b.image.get_width() / 2, 5 + b.image.get_height() / 2 + 80)
        rightedge -= (b.image.get_width() + 5)

    next_tower = TOWER_FILENAMES[0]

    cursor = Cursor(screen, TOWER_FILENAMES[0],
                    (0, 0),
                    (1,1),
                    0.0, paths)

#.........这里部分代码省略.........
开发者ID:thouis,项目名称:works-in-progress,代码行数:101,代码来源:creeps.py



注:本文中的pygame.mixer.pre_init函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mixer.quit函数代码示例发布时间:2022-05-25
下一篇:
Python mixer.init函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap