How can I play multiple sounds at once in the iPhone SDK?
+1
A:
here is an example using AudioUnits. they might be a little complicated for your requirements, but then you never stated your requirements.
Aran Mulholland
2009-12-08 22:41:11
+1
A:
I have found if you don't require any advanced audio features AVAudioPlayer
and NSOperationQueue
work quite nicely.
NB: This example is adapted form a project and might contain some bugs
//sound1 and sound2 are NSData objects
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSError *error = nil;
AVAudioPlayer *player1 = [[AVAudioPlayer alloc] initWithData:sound1 error:&error];
AVAudioPlayer *player2 = [[AVAudioPlayer alloc] initWithData:sound2 error:&error];
if(error)
{
//Handle errors...
}
NSInvocationOperation *op1 = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(playSounds:) object:player1] autorelease];
NSInvocationOperation *op2 = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(playSounds:) object:player2] autorelease];
[queue addOperation:op1];
[queue addOperation:op2];
The playSounds
methods will look something like this:
- (void)playSounds:(id)data
{
AVAudioPlayer *player = (AVAudioPlayer *)data;
[player prepareToPlay];
[player play];
}
A note on efficiency, this will work fine on the simulator but the expensive operation on the device is the creation of the AVAudioPlayer
object, i.e.:
AVAudioPlayer *player1 = [[AVAudioPlayer alloc] initWithData:sound1 error:&error];
Therefore it is best to have all your sounds in one file and use the currentTime
property and the play
and stop
methods, to play the correct section of the sound file.
rjstelling
2009-12-08 23:02:33