views:

544

answers:

2

I've made a simple app, where I have a list of songs. The user taps a list entry and the song begins playing.

I've lifted the SoundEffect class from Apple's sample projects (e.g. Metronome, BubbleLevel). It seems to work fine with the following code:

// declare in the .h file
SoundEffect *audio;

// setup - when controller loads
audio = [SoundEffect alloc];

// play when user taps entry
NSBundle *mainBundle = [NSBundle mainBundle];   
[audio initWithContentsOfFile:[mainBundle pathForResource:@"entry1" ofType:@"mp3"]];
[audio play];

However, if the 'audio' object is already playing, I'd like to stop it before it starts playing the sound again. SoundEffect class does not have a stop method or I am simply missing something.

How do i stop the audio before playing it again?

+3  A: 

Why don’t you simply use AVAudioPlayer?

zoul
Thanks, I didn't know about this class. One gotcha about it is that if you [play] the file, then [stop] the audio, and then [play] again, it'll start playing where it left off. The trick is to set .currentTime to 0 when you stop.
AngryHacker
"set .currentTime to 0" -- Thanks for that!
bmoeskau
+1  A: 

The SoundEffect class is a wrapper around the C-based System Sounds API (see the .m file from the Bubble Level project), which is a simple "fire and forget" style API that doesn't provide a "stop" function. More info in the System Sounds Services Reference.

I also agree with (and have voted up) zoul's suggestion to use AVAudioPlayer. System Sounds are wholly inappropriate for long, encoded audio files like songs in MP3 files.

invalidname