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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.