Play sound files with pySFML

vegaseat 2 Tallied Votes 758 Views Share

Shows you how to play sound files with the pySFML module and Python.

''' sfml_play_sound.py
play sound files with the pySFML module

download Windows installers
Python27 --> pySFML-1.3.0.win32-py2.7.exe
Python33 --> pySFML-1.3.0.win32-py3.3.exe
from:
http://python-sfml.org/download.html
(OSX and Linux version are available too)

supported audio formats: 
ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, 
w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64
does not play .mp3 or .mid files

tested with Python27 and Python33  by  vegaseat  19dec2013
'''

import sfml as sf

def play_sound(sound_file):
    # load sound file into memory, used for shorter files
    buffer = sf.SoundBuffer.from_file(sound_file)

    # display sound informations
    print("{}:".format(sound_file))
    print("duration = {} seconds".format(buffer.duration))
    print("rate = {} samples/sec".format(buffer.sample_rate))
    ct = buffer.channel_count
    # uses plural option
    print("using {} channel{}".format(ct, ['', 's'][ct > 1]))

    # create a sound instance and play it
    sound = sf.Sound(buffer)
    sound.play();

    # loop while the sound is playing
    while sound.status == sf.Sound.PLAYING:
        # leave some CPU time for other processes
        sf.sleep(sf.milliseconds(100))

def play_music(sound_file):
    # load sound file with streaming, used for longer files
    music = sf.Music.from_file(sound_file)

    # display music informations
    print("{}:".format(sound_file))
    print("duration = {} seconds".format(music.duration))
    print("rate = {} samples/sec".format(music.sample_rate))
    ct = music.channel_count
    # uses plural option
    print("using {} channel{}".format(ct, ['', 's'][ct > 1]))

    # play it
    music.play();

    # loop while the music is playing
    while music.status == sf.Music.PLAYING:
        # leave some CPU time for other processes
        sf.sleep(sf.milliseconds(100))

if __name__ == "__main__":
    # pick sound file .wav .ogg .au you have in the working folder
    # or give full path name
    #sound_file1 = "brain.wav"
    sound_file1 = "rooster.au"
    #sound_file1 = "piano.ogg"
    #sound_file2 = "piano.ogg"
    sound_file2 = "DontGetMeWrong.ogg"
    
    play_sound(sound_file1)
    print('-'*40)
    sf.sleep(sf.milliseconds(1000))  # wait a second
    play_music(sound_file2)