playing a mp3 file in iOS app

user2444410 picture user2444410 · Jun 2, 2013 · Viewed 20.3k times · Source

I can't figure out how to play a music file in an iPhone game.

Im creating a Game and I am trying to figure out how to play music whenever the app is launched.

I tried this:

- (void)awakeFromNib {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"musicamenu" ofType:@"mp3"];

    AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

    [theAudio play];


}

Answer

Sam B picture Sam B · Jun 2, 2013

This is how you do it. In your v1AppDelegate.h file add

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface v1AppDelegate : UIResponder <UIApplicationDelegate>
{
    AVAudioPlayer *myAudioPlayer;
}

@property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;

@property (strong, nonatomic) UIWindow *window;

@end

Now in your v1AppDelegate.m file add this

#import "v1AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@implementation v1AppDelegate

@synthesize window = _window;

@synthesize myAudioPlayer;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //start a background sound
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Soothing_Music2_Long" ofType: @"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];    
    myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    myAudioPlayer.numberOfLoops = -1; //infinite loop
    [myAudioPlayer play];


    // Override point for customization after application launch.
    return YES;
}

If you wish to stop or start this music from anywhere else in your code then simply add this

#import "v1AppDelegate.h"    
- (IBAction)stopMusic
    {
        v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate.myAudioPlayer stop];
    }


    - (IBAction)startMusic
    {
        v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate.myAudioPlayer play];
    }