我该怎么做才能调用audioPlayerDidFinishPlaying:

时间:2012-03-22 11:15:31

标签: objective-c ios exc-bad-access avaudioplayer

我写了这个源程序。但我无法调用 audioPlayerDidFinishPlaying:方法。 播放声音后,几秒钟后“exc_bad_access”错误就会崩溃。

.h文件

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface SecondViewController : UIViewController<
AVAudioPlayerDelegate>{
    AVAudioPlayer *aPlayer;
}
@end

.m文件

-(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 个答案:

答案 0 :(得分:1)

这是我使用的完美工作,它可以帮助你。

-(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];
}