0

For some reason, the cleanupPlayer method is a little buggy and isn't releasing the audio player correctly. My application crashes from time to time, and I suspect it's due to a memory issue. Also, when I try to play an audio file twice (on button click), the second time the audio sometimes cuts out. I'm a bit of a newbie, so any help would be greatly appreciated!

Here is a snippet of code:

.h file:

@property (retain,nonatomic)AVAudioPlayer *player;

.m file:

-(void)playSound:(NSString *)fileName
{
    // Play
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:kSoundFileType]];
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    _player.delegate = self;
    [_player prepareToPlay];
    [_player play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self cleanupPlayer];
}   

-(void)cleanupPlayer
{
    if(_player != nil) {
    [_player release];
}
4

1 回答 1

0
try this...



-(void)playSound:(NSString *)fileName
{

    if (_player.isPlaying) {
        [_player stop];
    }

        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:@"mp3"]];
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        _player.delegate = self;
        [_player prepareToPlay];
        [_player play];

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self cleanupPlayer];
}

-(void)cleanupPlayer
{
    _player =nil;

}
于 2013-09-20T09:05:08.760 回答