2012-03-22 125 views
0

我寫了這個源程序。但我不能撥打 audioPlayerDidFinishPlaying:方法。 播放聲音後,幾秒鐘後會因「exc_bad_access」錯誤而崩潰。我應該怎麼做才能調用audioPlayerDidFinishPlaying:

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

回答

0

這是我用完美的作品,它應該幫助你。

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

...它出錯了,因爲您已將您的AVAudioPlayer聲明爲「aPlayer」,然後在您的audioPlayerDidFinishPlaying方法中調用「player」。 – 2012-03-23 16:11:51

相關問題