0

I want to know how to add background music to my app. My code so far:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Jaunty Gumption" ofType:@"mp3"]];
    AVAudioPlayer *backgroundMusic  = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile  error:nil];
    backgroundMusic.numberOfLoops = -1;
    [backgroundMusic play];
}

But when I launch the app nothing happens and I don't know why. I have included the AVFoundation an AudioToolbox frameworks. Any help would be appreciated. :) Thanks Matis

MatisDS
  • 91
  • 1
  • 11

1 Answers1

4

ARC is destroying your audio player before it gets any chance to output audio. When an audio player is about to be destroyed, it stops playing audio. Assign it to a strong property instead of a local variable, like so:

@interface MyClass : UIViewController

@property(nonatomic, strong) AVAudioPlayer *backgroundMusic;

@end

@implementation MyClass

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *musicFile = [[NSBundle mainBundle] URLForResource:@"Jaunty Gumption"
                                               withExtension:@"mp3"];
    self.backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile
                                                                  error:nil];
    self.backgroundMusic.numberOfLoops = -1;
    [self.backgroundMusic play];
}

@end

Doing this will keep the audio player alive at least as long as the view controller.

  • Thanks but when I use your code I get the error: No visible @interface for 'NSBundle' declares the selector'urlForResource:withExtension:' and the error: Use of undeclared identifier 'backgroundMusic' – MatisDS Jul 03 '13 at 18:39
  • 1
    @MatisDS My bad, fixed that now. When you want to refer to a property, prepend its name with `self.`, e.g. `self.backgroundMusic`. I recommend you read [Programming with Objective-C](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html). –  Jul 03 '13 at 18:40
  • I have changed my code and now I am getting the error: No visible @interface for 'NSBundle' declares the selector 'urlForResource:withExtension:' – MatisDS Jul 03 '13 at 18:45
  • @MatisDS It's `URLForResource:withExtension:`, not `urlForResource:withExtension:`. –  Jul 03 '13 at 18:46