I have 10 sounds in one view. And they all play, ho开发者_Go百科wever only one sound can play at a time. I want it so you can tap the sounds you want to play, and they all play at the same time. But at the moment when you press a sound it plays, then you go to press another sound and the sound previously stops.
Here is the code which I have used for the sounds
- (IBAction)oneSound:(id)sender; {
NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"wav"];
if (theAudio) [theAudio release];
NSError *error = nil;
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
if (error)
NSLog(@"%@",[error localizedDescription]);
theAudio.delegate = self;
[theAudio play];
}
- (IBAction)twoSound:(id)sender; {
NSString *path = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"wav"];
if (theAudio) [theAudio release];
NSError *error = nil;
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
if (error)
NSLog(@"%@",[error localizedDescription]);
theAudio.delegate = self;
[theAudio play];
}
- (IBAction)threeSound:(id)sender; {
NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"];
if (theAudio) [theAudio release];
NSError *error = nil;
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
if (error)
NSLog(@"%@",[error localizedDescription]);
theAudio.delegate = self;
[theAudio play];
}
Thanks!
This probably causes the problem:
if (theAudio) [theAudio release];
The AVAudioPlayer cannot continue playing after it's released.
What basically happens:
- Button click
- theAudio is initialized
- theAudio starts playing
- Another button click
- theAudio is released and therefor stops playing
- theAudio is initialized with another sound
- theAudio starts playing
Seems like your theAudio is global and you instantiate it again in each method. Transform it in a local variable or define 3 (or how many you need).
精彩评论