Wednesday, 16 January 2013

Recording Animal Sounds


Recording Animal Sounds

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.
Example 27: Animal sounds
import appuifw, audio
animals = [u"dog", u"cat", u"cow"]
def record_animal_sounds():
for animal in animals:
noise = audio.Sound.open("e:\\" + animal + ".wav")
if appuifw.query(u"Record sound of a " + animal, "query"):
noise.record()
appuifw.query(u"Press OK to stop recording", "query")
noise.stop()
noise.close()
def select_sound():
global funny_noise
SOUND 83
funny_noise = None
while True:
index = appuifw.popup_menu(animals, u"Select sound:")
if funny_noise:
funny_noise.stop()
if index == None:
break
else:
play_animal_sound(u'e:\\ + animals[index] + '.wav')
def play_animal_sound(soundfile):
global funny_noise
funny_noise = audio.Sound.open(soundfile)
funny_noise.play()
record_animal_sounds()
select_sound()



This time, you have to record sounds of the three animals when the
script starts. This is handled by the function record animal sounds()
which loops over the list of animals, animals. After this, the function
select sound() presents a menu that lets you choose a sound to
play.
Note that the sounds are saved to the root of the memory card, that is,
the E: drive. If you do not have a memory card, you can change the path,
for instance, to C:\\Python.
The playing of a sound is handled by the function play animal
sound(). Note that here we declare the variable funny noise as
global. This variable contains the sound object that is now playing. If
funny noise was not global, we would not be able access it after the
function play animal sound() returns, so stopping the sound would
be impossible. As the variable is declared global, it stays alive even after
the function returns, so we can stop the sound once the user chooses
the next sound to be played. This example exits when you cancel the
playback dialog.










1 comment:

  1. After importing the Application User Interface Module Frame Work, Using Different brackets after each line is not recommended. Unless single or double quotting. Users tends to have "invalid syntax" when running scripts

    ReplyDelete