Example Sound recorder

import appuifw, audio, os

MENU = [u"Play sound", u"Record sound", u"Delete sound"] SOUNDFILE = u"E: \\sound.wav" sound = None

while True:

index = appuifw.popup_menu(MENU, u"Select operation") if sound:

sound.stop() sound = audio.Sound.open(SOUNDFILE) if index == 0:

sound.record()

appuifw.query(u"Press OK to stop recording", "query") sound.stop() elif index == 2:

os.remove(SOUNDFILE) else:

break

The program starts by displaying a popup menu, as shown in Figure 5.1, that lets the user choose the desired operation. If you attempt to play a sound before one has been recorded, the program crashes as the file SOUNDFILE cannot be found. Chapter 6 gives you some ideas on how to handle situations like this properly.

The function sound.record() starts recording. The recording continues until sound.stop() is called. Since we want the user to decide when to stop, we present a dialog that blocks the execution until the user selects OK.

If the sound file already exists when recording starts, the new sound is appended to the end of the existing file. You can hear this easily by repeating the 'Record sound' operation several times and then listening to the sound. If you want to start recording from scratch, the previous file must be deleted first. This can be done with the os.remove() function, which deletes the file whose name is given in the parameter. This function is called if the user chooses the 'Delete sound' operation from the menu. Note that you need to import the os module to use this function.

As the program operates within an infinite loop, the popup menu is shown again once an operation finishes. Note that sound.play() only starts the playing and does not wait for it to finish, so a new dialog may be shown although the sound is still playing. We stop playing, however, once the next operation has been chosen, as it is not a good idea to

Copyright (c) 1995-2001 Corporation for National Research Initiatives. Ail Rights Reserved.

Play sound

Figure 5.1 Sound recorder

Back

Figure 5.1 Sound recorder execute several record() and play() operations simultaneously on the same sound object. The program exits when you cancel the popup menu.

Example 27 extends the previous sound recorder by recording sounds to several sound files instead of only one. The example lets you record and play sounds of animals, namely the sound of a dog, a cat and a cow. If you have a toddler, this might be a good way to introduce the wonderful world of mobile programming.

0 0

Post a comment

  • Receive news updates via email from this site