Tuesday, June 30, 2009

Playing .wav files on Windows, Mac, Linux

Playing .wav files in the current directory.

Windows


import glob, winsound, random
wavfiles = glob.glob("*.wav")
wavfile = random.choice(wavfiles)
while(True):
raw_input()
wavfile = random.choice(wavfiles)
winsound.PlaySound(wavfile, winsound.SND_FILENAME)

Mac (got the idea here)

from AppKit import NSSound
from time import sleep
import glob, random
wavfiles = glob.glob("*.wav")
while(True):
raw_input()
wavfile = random.choice(wavfiles)
s = NSSound.alloc()
s.initWithContentsOfFile_byReference_(wavfile, True)
s.play()
while s.isPlaying():
sleep(0.1)
s.stop()

Linux (needs play command)

import os, glob, random
wavfiles = glob.glob("*.wav")
wavfile = random.choice(wavfiles)
while(True):
raw_input()
wavfile = random.choice(wavfiles)
os.system("play -q " + wavfile)

No comments: