Stop background sound when leaving the initial View Controller - ios

My app has looped background music that plays over the initial view controller.
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:#"%#/bgMusic.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
}
When leaving the initial view controller I want the music to stop, so I used the code below, but instead it restarts.
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[audioPlayer stop];
}

Related

Memory issue with AVAudioPlayer

For some reason, the cleanupPlayer method is a little buggy and isn't releasing the audio player correctly. My application crashes from time to time, and I suspect it's due to a memory issue. Also, when I try to play an audio file twice (on button click), the second time the audio sometimes cuts out. I'm a bit of a newbie, so any help would be greatly appreciated!
Here is a snippet of code:
.h file:
#property (retain,nonatomic)AVAudioPlayer *player;
.m file:
-(void)playSound:(NSString *)fileName
{
// Play
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:kSoundFileType]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
if(_player != nil) {
[_player release];
}
try this...
-(void)playSound:(NSString *)fileName
{
if (_player.isPlaying) {
[_player stop];
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
_player =nil;
}

My apps is crashing when player is play

I have a very simple app that is supposed to only play an audio file on view. Instead my Xcode is crashing.
I am using Xcode version 6. I have implemented the AVFoundation Framework
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"Crowd_cheering"
ofType:#"m4a" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.player play];
}
//Try like this with error condition:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Moderato"
ofType:#"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
//Before that add import AVFoundation/AVFoundation.h and add delegate AVAudioPlayerDelegate
//then Implement the AVAudioPlayerDelegate Protocol Methods like this
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
}
Make sure u connected ur play button properly or not and also check whether you Added an Audio File to the Project Resources properly.

Trigger AVAudioPlayer to stop all sounds and play selected except when playing(selected) button is clicked

I am creating a sound board app that plays one sound at a time. I would like a UIButton to be able to stop all other sounds playing and start playing its own sound when clicked. I have a single AVAudioPlayer set up to play all sounds (I change the sound file url when clicked and since I only want one sound at a time playing this is not an issue). I would like to know how to stop all other sounds and play the sound according to the button pressed, but if the button clicked is the button with the sound currently playing, the button only stops the sound. I know this is achievable through going to separate audioplayers and triggering the stop event but I want to avoid copy and pasting code and to stay efficient as possible, plus I only want / need a single audioplayer. Here is my code:
- (IBAction)play {
if (audioPlayer.playing == NO) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/k.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
[audioPlayer release];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
AVAudioSession *audiosession = [AVAudioSession sharedInstance];
[audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioPlayer play];
[start setTitle:#"Stop" forState:UIControlStateNormal];
}
else
if (audioPlayer.playing == YES) {
[audioPlayer stop];
[start setTitle:#"Start" forState:UIControlStateNormal];
}
}
- (IBAction)play2 {
if (audioPlayer.playing == NO) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/chicken.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
[audioPlayer release];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
AVAudioSession *audiosession = [AVAudioSession sharedInstance];
[audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioPlayer play];
[start2 setTitle:#"Stop" forState:UIControlStateNormal];
} else
if (audioPlayer.playing == YES) {
[audioPlayer stop];
[start2 setTitle:#"Start" forState:UIControlStateNormal];
}
}
Any help is appreciated. Thank you in advance!
Just do this
-(void)stopAudio{
if(audioPlayer && [audioPlayer isPlaying]){
[audioPlayer stop];
audioPlayer=nil;
}
}
And call this function on every click..
- (IBAction)play2 {
[self stopAudio];
//Do your Stuffs
}
when your button is clicked stop your audio player and assign your new song url and then play it.Write this code when you click on button to play song.
if(audioPlayer.isPlaying)
[audioPlayer stop];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSURL *url = [NSURL fileURLWithPath:YourSoundURL];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.delegate=self;
[audioPlayer play];
[start2 setTitle:#"Stop" forState:UIControlStateNormal];

stop a sound from playing objective c?

- (void)viewDidLoad {
[super viewDidLoad];
[audioPlayer stop];
NSString *Path = [[NSBundle mainBundle] pathForResource:#"Keep the Shoes Moving" ofType: #"m4a"];
NSURL *URL = [[NSURL alloc] initFileURLWithPath: Path];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; }
What happens with this is every time I navigate back to this viewController it plays another track. So then I have two tracks playing over each other. How would I get this to stop??
Store your AVAudioPlayer instance in a property and call it’s stop method when you want it to stop playing.

IOS: AVAudioPlayer management memory

I have this method to play an mp3:
- (void) playSound:(NSString*)sound{
NSString *path = [NSString stringWithFormat:#"%#/%#",
[[NSBundle mainBundle] resourcePath],
sound];
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:nil];
[player prepareToPlay];
[player play];
}
everytime I call this method I get a new string "sound" and then I must alloc everytime this AVAudioplayer "player"; I want release it when I stop it or when it finish...is it possible?
Try the below instruction
yourViewController.h
#interface yourViewController : UIViewController <AVAudioPlayerDelegate>
yourViewController.m file for add function
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//play finished
}
Declare the AVAudioPlayer Object below code
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"audio" ofType:#"mp3"]] error:NULL];
audioPlayer.delegate = self;
audioPlayer.currentTime=0.0f;
[audioPlayer prepareToPlay];
[audioPlayer play];
Thanks..!
Take a look at AVAudioPlayerDelegate.
It has the methods audioPlayerDidFinishPlaying:successfully: and audioPlayerDecodeErrorDidOccur:error: that should let you do what you want.

Resources