Question

I am trying to make a background music in my game with AVAudioPlayer, so I set this code at the initWithSize method of my SKScene:

//SETTING BACKGROUND MUSIC//
NSError * err = nil;
NSURL * musicFile = [[NSBundle mainBundle] URLForResource:@"Cosmic Rush" withExtension:@"m4a"];
music = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:&err];
if(err)
{
    NSLog(@"%@", [err userInfo]);
    return;
}
[music prepareToPlay];
music.numberOfLoops = -1;
[music setVolume:0.5];
//SETTING BACKGROUND MUSIC//

Then, in another method: [music play]; However, the sound never plays, and I have tried all sort of extensions: .mp3, .caf, .mp4 etc. I have also checked people who had the same problem, but none of the solutions that solved their problems worked with mine.

Was it helpful?

Solution

there is a easier way to add background music to your scene. i use the following steps and works just as good as any other methods and it is easier.

import the @import AVFoundation; at the top of your scene.

add it as a property right after your @implementation.

AVAudioPlayer *_backgroundMusicPlayer;

then declare a method for the music

- (void)playBackgroundMusic:(NSString *)filename
{
    NSError *error;
    NSURL *backgroundMusicURL =
    [[NSBundle mainBundle] URLForResource:filename
                            withExtension:nil];
    _backgroundMusicPlayer =
    [[AVAudioPlayer alloc]
     initWithContentsOfURL:backgroundMusicURL error:&error];
    _backgroundMusicPlayer.numberOfLoops = -1;
    [_backgroundMusicPlayer prepareToPlay];
    [_backgroundMusicPlayer play];
}

after that create a reference to that method in your -(id)initWithSize:(CGSize)size like the following

[self playBackgroundMusic:@"bgMusic.mp3"];

that should take care of the background music for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top