Wednesday, 16 January 2013

Recording Sounds


Recording Sounds

Now we turn your phone into a lo-fi music studio by showing how
to record sounds with the audio module. Although a phone supports
playing a wide range of different sound formats, it can typically record
only WAV and AMR files.
Sounds are recorded using the same audio.Sound object that was
used for playback. In Example 26, we make a simple program that lets
you record and play a single sound.


Example 26: 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.play()
elif index == 1:
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

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












No comments:

Post a Comment