Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sound not playing with AVAudioPlayer

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.

like image 285
Aen Tan Avatar asked Apr 01 '12 09:04

Aen Tan


1 Answers

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.

like image 67
3lvis Avatar answered Sep 28 '22 00:09

3lvis