[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] loading ogg or mp3 files



If you want, I can post music.py, a set of functions for working with
music relatively easily.


Sure!

This might be useful to you:


## Music.py ## Easy functions for using music and sound in Python/Pygame. ## By Kris Schnee, borrowing heavily from Pygame's docs and examples.

import pygame, os.path
pygame.mixer.init()

MUSIC_ON = True
MUSIC_DEFAULT_SONG = "xenogears-village.mid" ## MIDI or MP3, in \graphics
PRELOAD_SONG = True ## Load default music to prevent a crash in case user
                    ## stupidly calls CueMusic(None) w/o loading a song?

def ToggleMusicEnabled(music_on=None):
    if music_on == True:
        MUSIC_ON = True
    elif music_on == False:
        MUSIC_ON = False
    else:## Toggle by default
        if MUSIC_ON:
            MUSIC_ON = False
        else:
            MUSIC_ON = True


def CueMusic(name=None, interrupt=True): ## If "interrupt" is True, the new song will play ## even if one is already playing. ## If "name" is None, the same song will play again. ## Warning: If no music has been loaded, calling this w/o name ## will cause a crash. global MUSIC_ON if not MUSIC_ON: return ## Never mind. if not interrupt: if pygame.mixer.music.get_busy(): return ## It's busy; go away.

    pygame.mixer.music.stop()
    if name:
        pygame.mixer.music.load(name)
    pygame.mixer.music.play()

def StopMusic():
    pygame.mixer.music.stop()

def PlaySound(sound):
    if type(sound) is str: ## Have to load it first.
        x = pygame.mixer.Sound(SOUND)
    else:
        x = sound
    x.play()

def QuitMusic():
    """Shuts off Pygame's music code."""
    pygame.mixer.music.stop()
    pygame.mixer.quit()

##### AUTORUN #####
if __name__ == '__main__':
print "Now playing default music as a test. Enjoy. (StopMusic() to quit.)"
CueMusic(os.path.join("sound",MUSIC_DEFAULT_SONG))
else:
if PRELOAD_SONG:
pygame.mixer.music.load(os.path.join("sound",MUSIC_DEFAULT_SONG))
StopMusic()