8

I created a custom class to handle audio playback.

AudioPlayback.h

#import <Foundation/Foundation.h>
#import "AVFoundation/AVAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>

@interface AudioPlayback : NSObject <AVAudioPlayerDelegate> {

    AVAudioPlayer   *player;

    BOOL playing;
    NSTimeInterval duration;    

}
@property (nonatomic, assign) AVAudioPlayer *player;
@property (readonly) BOOL playing;
@property (readonly) NSTimeInterval duration;

-(NSTimeInterval)GetSoundFileDuration:(NSString *) sound_file_name;
-(void)PlaySoundFile:(NSString *) sound_file_name;
-(void)play;
-(void)stop;

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
@end

Then, in AudioPlayback.h

#import "AudioPlayback.h"

@implementation AudioPlayback

@synthesize player;

-(id)init
{
self = [super init];
if (self != nil)
{
    player = [[AVAudioPlayer alloc] init];
    [player initWithContentsOfURL:nil error:nil];
    player.delegate = self;
}
return self;
}

-(void)PlaySoundFile:(NSString *) sound_file_name
{
    NSURL *sound_file = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:sound_file_name ofType:@"mp3"]];

    [player initWithContentsOfURL:sound_file error:nil];
    [player prepareToPlay];
    [player play];
    [sound_file release];
}

...

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"audioPlayerDidFinishPlaying");
}

The callback never triggers. Am I missing anything obvious?

1 Answer 1

34

I think "player.delegate = self" is call too early. You "initWithContentsOfURL" again in your "PlaySoundFile", which I think that cause the problem.

Try to put "player.delegate = self" before the "[player prepareToPlay]" in your "PlaySoundFile" method

3
  • Arkchong is correct. You are re-initializing your player, but not re-setting the delegate. Commented Apr 18, 2011 at 5:10
  • Yup. That was it. Just couldn't see it. Thanks!
    – martin's
    Commented Apr 18, 2011 at 5:47
  • nice job! i had that same problem after changing contents of the player. thanks! Commented Jan 3, 2013 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.