Archived:How to play a sound file in PySymbian
This snippet shows how to play an audio file in Python and presents some of the options available.
Note: The method current_volume is not available for S60 1st Edition.
Valid file formats must be used. Their availability may vary from one device generation to another and they tipically include WAV, AMR, MP3, AAC, RA.
The optional parameter that is passed to the play() method of a Sound object represents the number of times the file will be played (1 by default). It can be an integer or the KMdaRepeatForever data item, which is for continous playback.
import appuifw, e32, audio
app_lock = e32.Ao_lock()
#Define the exit function
#Close the Sound object
appuifw.app.exit_key_handler = quit
file_path = u"C:\\Data\\Sounds\\Digital\\mysound.mp3"
#The path of the file that is to be played
#Open the sound file
s = audio.Sound.open(file_path)
#Play it indefinitely
#Wait for the user to request the exit
The sound file is played for the specified number of times.
Playing a Sound object in a function doesn't work because it goes out of scope when the function returns. If the Sound object goes out of scope, the sound stops playing. This will not work:
s = audio.Sound.open(f)
The solution is to make the Sound object a global variable so that it stays in scope when the function returns. This will work:
s = audio.Sound.open(f)
The Sound object method stop() is used to stop playback. The Sound object method duration() returns the file's duration in microseconds. The Sound object methods current_position() and set_position(microseconds) return and set the current buffer position, respectively.
The Sound object methods current_volume(), set_volume(volume) and max_volume() return and set the current volume and return the maximum volume of the device, respectively.
The Sound object method state() returns the current state of the object, which can be one of the following:
The Sound object has been constructed but no audio file is open.
An audio file is open but no playing or recording operation is in progress.
An audio file is playing.
An audio file is being recorded.
There is currently no method that pauses the playback of an audio file. The solution is:
- Use current_position() to find out the current position
- Use stop() to stop the playback
- Use set_position() to set the position to the one that was retrieved at step 1
- Use play() to resume playing the file as if it had been paused