Python ticking clock – Periodically play a ticking sound

March 11, 2010 at 11:17 pm Leave a comment

The following python script will periodically play a ticking sound after a given pause. This is can be useful for timing things when you are unable to start a timer – for example if you are practicing balancing a walking-stick on your nose on your own.

#!/usr/bin/env python
import ao
import ogg.vorbis
import os
import sys
from time import sleep, time

def switch_off_buffering():
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
switch_off_buffering()

PERIOD = 2
PAUSE = 5
SOUND = "/usr/share/sounds/gnome/default/alerts/sonar.ogg"

filename = 'test.ogg'

class OggSample(object):
    def __init__(self, filename):
        id = ao.driver_id('esd')
        self.vf = ogg.vorbis.VorbisFile(filename)
        self.device = ao.AudioDevice(id)

    def play(self):
        while 1:
            buff, bytes, _ = self.vf.read(4096)
            if bytes != 0:
                self.device.play(buff, bytes)
            else:
                self.vf.time_seek(0)
                return

def repeat(pause, period):
    sample = OggSample(SOUND)

    sleep(pause)
    tick_time = time()
    while True:
        sys.stdout.write(".")
        sample.play()
        tick_time += period # avoid drift
        sleep(tick_time - time())


DEFAULT_DELAY = 5
DEFAULT_PERIOD = 2

def usage(stream):
    print >>stream, "ticking-count [DELAY seconds] [PERIOD seconds]"
    print >>stream, "Default delay: %s seconds" % DEFAULT_DELAY
    print >>stream, "Default period: %s seconds" % DEFAULT_PERIOD

if __name__ == '__main__':
    args = sys.argv[1:]
    if '-h' in args or '--help' in args:
        usage(sys.stdout)

    if len(args) == 0:
        delay, period = DEFAULT_DELAY, DEFAULT_PERIOD
    elif len(args) == 1:
        delay, = args
        period = DEFAULT_PERIOD
    elif len(args) == 2:
        delay, period = args
    else:
        usage(sys.stderr)
    repeat(delay, period)

Advertisements

Entry filed under: Uncategorized. Tags: , , .

Playing an ogg file on linux using python Comparing wikis

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


March 2010
M T W T F S S
« Feb   Apr »
1234567
891011121314
15161718192021
22232425262728
293031  

%d bloggers like this: