Showing posts with label pyglet. Show all posts
Showing posts with label pyglet. Show all posts

Thursday, November 7, 2013

A simple alarm clock in Python (command-line)

By Vasudev Ram



(Updated the post after a while, so it may show up twice in some feed readers (but with more info), sorry ...)

I had a need to set alarms for myself while working at the computer, to remind me to stop the current task and do some other task. Was using my smartphone's alarm clock app, but found that the volume was a bit too high, even at the lowest volume setting. So I thought of writing a simple alarm clock in Python as a command-line utility. Here it the code for it:
# alarm_clock.py

# Description: A simple Python program to make the computer act 
# like an alarm clock. Start it running from the command line 
# with a command line argument specifying the duration in minutes 
# after which to sound the alarm. It will sleep for that long, 
# and then beep a few times. Use a duration of 0 to test the 
# alarm immediiately, e.g. for checking that the volume is okay.

# Author: Vasudev Ram - http://www.dancingbison.com

import sys
import string
from time import sleep

sa = sys.argv
lsa = len(sys.argv)
if lsa != 2:
    print "Usage: [ python ] alarm_clock.py duration_in_minutes"
    print "Example: [ python ] alarm_clock.py 10"
    print "Use a value of 0 minutes for testing the alarm immediately."
    print "Beeps a few times after the duration is over."
    print "Press Ctrl-C to terminate the alarm clock early."
    sys.exit(1)

try:
    minutes = int(sa[1])
except ValueError:
    print "Invalid numeric value (%s) for minutes" % sa[1]
    print "Should be an integer >= 0"
    sys.exit(1)

if minutes < 0:
    print "Invalid value for minutes, should be >= 0"
    sys.exit(1)

seconds = minutes * 60

if minutes == 1:
    unit_word = " minute"
else:
    unit_word = " minutes"

try:
    if minutes > 0:
        print "Sleeping for " + str(minutes) + unit_word
        sleep(seconds)
    print "Wake up"
    for i in range(5):
        print chr(7),
        sleep(1)
except KeyboardInterrupt:
    print "Interrupted by user"
    sys.exit(1)

# EOF

Run it without any command line arguments to see how to use it:

C:> python alarm_clock.py

or

C:> alarm_clock.py

Use the first version of the command above, if your Python interpreter is not registered with the OS as the default application to run .py files, and the second version if it is registered. Usually the latter is the case, so you can omit the word python at the beginning of the command. The square brackets shown in the usage message (see the code) are not to be typed literally, they are there to indicate that the word within them is optional (a standard convention used on UNIX).

You can pass an argument of 0 for the duration, to test the alarm clock immediately, e.g. to see if the volume suits you or not. If not, increase or decrease the volume of your computer speakers.

I find this simple alarm clock program more convenient to use (when at my computer, of course) than either my smartphone's alarm clock app, or my traditional (physical) alarm clock like the one in the image above :-) (*)

I just have to keep one command window open, run that program in it, e.g.:

alarm_clock.py 30

to remind me to change tasks after 30 minutes. And when I want to set and run the alarm again, I just hit up arrow, change the time at the end of the command if needed, and hit Enter.

In fact, on my machine, I also created a batch file called alarm.bat, which accepts an argument and passes it to alarm_clock.py, so all I really have to type at the command line is:

alarm 30

(*) (Okay, I don't really have one of those old-fashioned alarm clocks; I have a modern plastic one. But I'd like to pick up one of those old-fashioned pocket watches like the one below, at some antique or second-hand shop some day. My grandfather had one of those ...

old-fashioned pocket watch

The tool uses the print chr(7) method to make the beeps. I did this to make it portable between Windows and Linux. It is possible to use the winsound module (only on Windows) for making the sound instead. See my earlier post about Python's winsound module: Try the Python WinSound API. It would also be possible to use other sound libraries instead, of course, on either Linux or Windows. For example, check out my earlier post about PyAudio (which also has a link to an earlier post about pyglet, another sound library option).

I'd also earlier written a digital clock (not an alarm clock, just a clock display) in 3 lines of Delphi code :-)

Of course, there are many variations and improvements possible on an alarm clock utility, such as having a GUI, making it look like a real alarm clock, and others. I may work on some of those at some point later. Meanwhile, this simple one works well enough for my current needs.


- Vasudev Ram - Dancing Bison Enterprises

Read other posts about Python on my blog.

Read other posts about utilities on my blog.

Contact me





O'Reilly 50% Ebook Deal of the Day

Sunday, April 28, 2013

PySynth, a pure Python music synthesizer


By Vasudev Ram

PySynth is a music synthesizer library written in Python. (*)

Excerpt from the site:

[ There are three variants: PySynth A is faster, only needs Python itself, and sounds more like a cross between a flute and organ. PySynth B is more complex in sound and needs NumPy. It's supposed to be a little closer to a piano. (No competition for Pianoteq of course, but a reasonable fit for keyboard music.) Finally, PySynth S is more comparable to a guitar, banjo, or harpsichord, depending on note length and pitch.

The current release of the synthesizer is monophonic, i.e. it can only play one note at a time. (Although successive notes can overlap in PySynth B and S, but not A.) However, two output files can be mixed together as in the case of the stereo files below. ]

(*) Interestingly, the Changes section of the above linked PySynth page seems to indicate that PySynth uses both Pyglet and PyAudio, both of which I had blogged about some time ago:

Playing an MP3 with pyglet and Python is easy

PyAudio and PortAudio - like ODBC for sound

Here is PySynth on Github

PySynth supports ABC notation and can generate WAV audio files.

Here is an example tune:

D D C C B A G

and here is a PySynth program to play that tune as a WAV file:
# pysynth-ddccbag.py

import pysynth

test = ( ('d', 4), ('d', 4), ('c', 4), ('c', 4), ('b', 4), ('a', 4), ('g', 3) )
pysynth.make_wav(test, fn = "ddccbag.wav")
For some reason the last note seems to get partially cut off on my PC. Not sure whether that is a bug or a feature :-) or something to do with my hardware. Maybe the latter, since I'm using my laptop's built-in speakers.

Run that program as:
python pysynth-ddccbag.py 

Then play the generated WAV file ddccbag.wav in a music player, such as VLC or some other one.

Here are a few better examples of sound synthesis by PySynth - the links are to MP4 files, which you can download and play without needing Python or PySynth:

The Sailor’s Hornpipe — PySynth S

Bach: Jesu, Joy of Man’s Desiring — PySynth S (treble) and B (bass)

Also check my recent post: Play the piano on your computer with Python.

If you want to try it out, note that the program has a couple of bugs, related to the frequencies of notes, since I am not musically trained; I just wrote it for fun and as an experiment. Though some of the post comments gave some background and suggested corrections, they did not seem to be sure, and corrected themselves, so I have not implemented any of those suggestions yet.


Enjoy.

- Vasudev Ram - Dancing Bison Enterprises

Thursday, July 9, 2009

Playing an MP3 with pyglet and Python is easy

By Vasudev Ram

pyglet is a cross-platform windowing and multimedia library for Python.

Playing an MP3 with pyglet and Python is as easy as this:

import pyglet

music = pyglet.resource.media('your_file.mp3')
music.play()

pyglet.app.run()

Some of the features of pyglet (from the pyglet site):

  • No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation.

  • Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games.

  • Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid.


Another good thing about pyglet is that it's a small download; also, installation went fast and without a hitch. Immediately after installing it (on Windows, with the bundled AVBin), I was able to run the above code. No configuration was required. AVbin is a thin wrapper around FFmpeg, which is a cross-platform solution to record, convert and stream audio and video.

I've not yet checked whether it's possible to pause and continue the played audio, though, either programmatically or via some graphical controls of pyglet.

UPDATE: Yes, GUI controls are possible. See the code for this audio and video player with simple GUI controls, in the link titled "examples/media_player.py" near the end of this page.

Currently listening to an MP3 of a tech interview that's being played by the above pyglet program.



- Vasudev Ram - Dancing Bison Enterprises.