1
votes

I'm facing a small issue with playing sounds upon loading of the view (and ultimately upon other actions that are performed if this code works)

The Problem: The sound does not play on the phone when the view is loaded. HOWEVER, I can hear the sound from my iphone if I step through the code after adding a breakpoint on:

[click play]

I have obtained the following code from an online tutorial and copied it to my viewDidLoad method:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]                                                                                                                  pathForResource:@"States" ofType:@"mp3"]];
    AVAudioPlayer *click  = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile  error:nil];
    [click play]; // Breakpoint is here

}

Things I've done:

  • Imported AudioToolbox/AudioToolbox.h and AVFoundation/AVFoundation.h in my header file
  • Executed the code with and without breakpoints --> With the breakpoints and the stepping through I can hear the sound; without I cant.

I would greatly appreciate it if I can get some suggestions or inputs to try it. Or even another way to implement audio in my application

Thank you.

2
try viewdidappear onceSaad Chaudhry
You might be better off adding click as a property of the classGruntcakes

2 Answers

1
votes

Your audio player object, "click", will be deallocated as soon as viewDidLoad finishes, since it's assigned to a local variable. You need to create an ivar or property for your player.

0
votes

musicFile doesn't contain a URL for a music file (or, indeed, any file). It contains the URL of Application itself. What you want to do is something more along the lines of:

musicFile = [[NSBundle mainBundle] URLForResource:@"musicFile" withExtension:@"caf"];

Also, for playing small short audio clips, you probably just want to use AudioServices

One-time initialization (in viewDidLoad, or statically):

static SystemSoundID    sound;
static dispatch_once_t  onceToken;

dispatch_once(&onceToken, ^{
    NSURL*      url = [[NSBundle mainBundle] URLForResource:@"statusChanged" withExtension:@"caf"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &sound);
});

Then to play the sound:

AudioServicesPlaySystemSound(sound);