Sound not playing with AVAudioPlayer

Aen Tan picture Aen Tan · Apr 1, 2012 · Viewed 24.2k times · Source

I've searched and I believe my problem is quite unique. I'm aware of the Simulator 5.1 bug when using AVAudioPlayer which isn't my problem. I'm running on a iOS 5.1 device.

Here's my header file:

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

-(IBAction)pushBell;

@end

and my implementation file:

#import "BellViewController.h"

@interface BellViewController ()

@end

@implementation BellViewController

-(IBAction)pushBell {

    NSString *soundPath =[[NSBundle mainBundle] pathForResource:@"bell1" ofType:@"caf"];
    NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
    NSError *error;

    AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
    [theAudio setDelegate:self];
    [theAudio setNumberOfLoops:0];
    [theAudio play];

}

@end

And I have a button in my .xib that plays the file.

To make sure I referenced my audio file correctly, I deliberately type a wrong file name and indeed I got an exception. To make sure the file is playable, I mailed it to myself and played it on the device.

When I tap the button I hear nothing. There are no errors. I don't know what is wrong.

More information iPhone 4 with iOS 5.1 Xcode 4.3.2 Audio is about 700kbps converted to .caf format using afconvert from a big .wav file.

Answer

3lvis picture 3lvis · Apr 1, 2012

SOLVED.

1.- Check if your file has been added to "Copy Bundle Resources" in Build Phases. Copy Bundle Resources

2.- ViewController.m

#import <AVFoundation/AVAudioPlayer.h>

@interface ViewController ()
@property (nonatomic, strong) AVAudioPlayer *theAudio;
- (IBAction)pushBell;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *soundPath =[[NSBundle mainBundle] pathForResource:@"beep-beep" ofType:@"caf"];
    NSURL *soundURL = [NSURL fileURLWithPath:soundPath];

    NSError *error = nil;
    self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
}

- (IBAction)pushBell {
    [self.theAudio play];
}

3.- Connect the IBAction to your button in Interface Builder.

Done.