问题
I wrote this source program . But I can't call audioPlayerDidFinishPlaying: method. After playing the sound, which crashes by "exc_bad_access" error after a few seconds.
.h file
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface SecondViewController : UIViewController<
AVAudioPlayerDelegate>{
AVAudioPlayer *aPlayer;
}
@end
.m file
-(void)playSound{
NSString *soundName = @"red";
NSError *error = nil;
NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:soundName withExtension:@"mp3"];
aPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
if (error != nil) {
NSLog(@"audio_player initialized error :(%@)",[error localizedDescription]);
[aPlayer release];
error=nil;
return;
}
NSLog(@"player Ok!");
aPlayer.delegate = self;
[aPlayer prepareToPlay];
aPlayer.volume=1.0f;
[aPlayer play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player release];
}
回答1:
This is what I use that works perfectly, it should help you.
-(void)playSound{
NSString *name = [[NSString alloc] initWithFormat:@"red"];
NSString *source = [[NSBundle mainBundle] pathForResource:name ofType:@"mp3"];
if (data) {
[data stop];
data = nil;
}
data=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: source] error:NULL];
data.delegate = self;
[data play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)data successfully:(BOOL)flag{
NSLog(@"my log");
[data release];
}
来源:https://stackoverflow.com/questions/9821195/what-should-i-do-to-call-audioplayerdidfinishplaying