Reputation: 1423
I have an app where I play an audio-file on launch in the View Controller. I also have a button that switches to my second view. My problem is that the audio continues to play even after I have switched view. Here's my code for ViewController.m:
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@end
@implementation ViewController
//When I go to this view, I want the audio to stop
- (IBAction)SwitchView:(id)sender {
SecondViewController *second = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:NULL];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"home_sound"
ofType:@"mp3"]];
NSError *error;
homeaudioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
homeaudioPlayer.delegate = self;
[homeaudioPlayer setNumberOfLoops: -1];
[homeaudioPlayer prepareToPlay];
}
[homeaudioPlayer play];
}
@end
How can I do this?
Thanks.
Upvotes: 0
Views: 65
Reputation: 3444
update your SwitchView code-
- (IBAction)SwitchView:(id)sender {
[homeaudioPlayer stop];
SecondViewController *second = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:NULL];
}
Upvotes: 3
Reputation: 127
Simply add [homeaudioPlayer stop]; to your switchView method. This should stop all sound that the player is playing.
Upvotes: 2