Objective-C background music - iphone

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.

Related

How do you make a sound file play automatically thought an iOS app and loop using Objective-C?

I am making a game for iPhone using objective-c. I have the music I want to play in a file in the project. I need to know how to make it begin playing when the app launches, and loop at the end. Does anyone know how to do this? Code examples would be great! Thanks.
you can use AVAudioPlayer in App Delegate.
First in your App Delegate .h file add these lines:
#import <AVFoundation/AVFoundation.h>
and these one:
AVAudioPlayer *musicPlayer;
In your .m file add this method:
- (void)playMusic {
NSString *musicPath = [[NSBundle mainBundle] pathForResource:#"phone_loop" ofType:#"wav"];
NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
[musicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
[musicPlayer prepareToPlay];
[musicPlayer play];
}
Finally call it in the didFinishLaunchingWithOptions method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
[self playMusic];
...
}
If you want to stop the music just:
[musicPlayer stop];
Aditionally you can check the Apple Documentation for AVAudioPlayer delegate for Handling Audio Interruptions http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html
PS: Remember to import the AVFoundation Framework to your project.
First import AVFoundation Framework to your project. Then insert the music file into your project.
declare
#import <AVFoundation/AVFoundation.h>
And then
AVAudioPlayer *audioPlayer;
NSURL *file = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:#"soundName" ofType:#"mp3"]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
audioPlayer.numberOfLoops = -1; // Infinite loops
[audioPlayer setVolume:1.0];
[audioPlayer prepareToPlay];
[audioPlayer start]
You can stop the sound before application goes to backgound by using
[audioPlayer stop];

How to auto play music as soon as my app starts?

I need some help with my app I have recently started. I am a very big starter to coding so please do help me, it'll mean a lot. I need a piece of music to play as soon as the user enters my app, i have followed other youtube tutorials but they only work for the older Xcode versions, so please help thank you so much.
How about putting it in you application didFinishLaunching but be sure to instantiate it in you .h and .m.
Something like this should do your problem:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:#"/YOURMUSICNAME.wav"];
NSLog(#"Path to play: %#", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
if( err ){
//bail!
NSLog(#"Failed with reason: %#", [err localizedDescription]);
}
else{
//set our delegate and begin playback
player.delegate = self;
[player play];
player.numberOfLoops = -1;
player.currentTime = 0;
player.volume = 1.0;
}
}
Then if you want to stop it:
[player stop];
or pause it :
[player pause];
and also import it in your header file:
#import <AVFoundation/AVFoundation.h>
EDIT:
You should to ofcourse declare it in your header, then synthesize it.
//.h and add the bold part:
#interface ViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *player;
}
#property (nonatomic, retain) AVAudioPlayer *player;
//.m
#synthesize player;
You can use the AVAudioPlayer. It pretty straight forward to use:
NSURL *path = [[NSURL alloc] initFileURLWithPath:[DataPersister getQualifiedPathForFileInDirectory:DataPersisterPathBundle fileName:#"music.mp3"]];
NSError *outError;
AVAudioPlayer *musicSound = [[AVAudioPlayer alloc] initWithContentsOfURL:path error:&outError];
[musicSound play];
[path release];
Remember to import
#import <AVFoundation/AVFoundation.h>
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/MUSIC.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
audioPlayer.volume = 1.0;
audioPlayer.currentTime = 2;
Use this at - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method will play music for sure
Happy Coding ;)

iOS - How to stop background music when changing views

How to stop background music when changing views? I have no clue. If i press a button which takes me to a new view, there is new background music. But the old background music (which goes in an infinite loop) keeps on going. Please help! also sample some code please, here is mine:
- (void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:#"MathMusic2" ofType:#"wav"];
AVAudioPlayer* theAudio= [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
theAudio.numberOfLoops = -1;
[super viewDidLoad];
}
I just need to know how to make the background music from the new view stop playing. And vice versa when i press the back button from the new view
Create a property for the AVAudioPlayer *theAudio so you can access the audioPlayer from any point in your class.
Header file of viewController
...
AVAudioPlayer *theAudio;
...
#property (nonatomic, retain) AVAudioPlayer *theAudio;
Implentation file of viewController
...
#synthesize theAudio;
...
- (void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:#"MathMusic2" ofType:#"wav"];
self.theAudio= [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]] autorelease];
theAudio.delegate = self;
[theAudio play];
theAudio.numberOfLoops = -1;
[super viewDidLoad];
}
If viewWillDisappear is called you can then just stop the audio with
- (void)viewWillDisappear
{
[theAudio stop];
}
it gaves errors in here :
"theAudio.delegate = self;" as something like assigning to id...
its yellow anyway..
still when i change view and go to another class music not stoping....

Audio Toolbox sound change problem

i'm new in iphone programin and i wrote a little animation program. i used audiotoolbox frame for sound and it was working.
But when i change the sound file. (deleted exfile from resources and folder and add the other file with the same name, same path)
but after changing sound is not working.
i also rechanged sound file with ex-file.But even ex file is not working.
(both are .wav type)
if you want i can write codes here.
thx for your help.
Have you tried rewriting the code?
You could also try using the AVFoundation Framework instead.
.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface AudioPlayerViewController : UIViewController {
AVAudioPlayer *audioPlayer;
}
#end
.m
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
}

iPhone SDK: How do you stop video playback with code?

In my app, I play a video using this simple code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:#"video" ofType:#"mp4"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMovie.movieControlMode = MPMovieControlModeHidden;
[theMovie play];
I'd like to know how to stop the video with code, I have tried [theMovie stop]; but this doesn't work, and an error is given, 'theMovie' undeclared (first use in this function) Which is understandable as the "theMovie" is only declared in the method that plays it. Has anyone got any ideas on how to stop it with out having to show the built in movie player controls? Any Help appreciated.
If you are creating that video in some method with that code and calling stop in some other method, the error shows up because theMovie only exists in the former method. You would need to set up an ivar or #property.
Check out this question.
EDIT:
A sample code (not tested):
#interface Foo : UIViewController {
MPMoviePlayerController *_theMovie;
}
#property (nonatomic, retain) MPMoviePlayerController *theMovie;
- (void) creationMethod;
- (void) playMethod;
- (void) stopMethod;
#end
#implementation Foo
#synthesize theMovie = _theMovie;
- (void) creationMethod {
NSString *moviePath = [[NSBundle mainBundle] pathForResource:#"video" ofType:#"mp4"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath]; // retain not necessary
self.theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
self.theMovie.movieControlMode = MPMovieControlModeHidden;
}
- (void) playMethod {
[self.theMovie play];
}
- (void) stopMethod {
[self.theMovie stop];
}
- (void) dealloc {
[_theMovie release];
}
#end
You would call the creationMethod somewhere to create your movie player. This is just an example of how a player could be placed in a property so you could use it across many methods but not necessarily a best practice. You could/should take a look at the iPhone documentation on declared properties.
I must note that I haven't used the MPMoviePlayerController class, though, so exact code might be different.