I use AVAudioPlayer to play sound on my app. I can stop the sound by just calling a method with [audioPlayer stop]; in it. But when I call the method from another ViewController the sound is not stopping. I already searched but I can't get the right answer. What I want is to stop the sound from another ViewController. Can someone help me? I am new to iOS.
I used this to add my sound file:
//Declare the audio file location and settup the player
NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:#"alarm" withExtension:#"wav"];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[audioPlayer setNumberOfLoops:-1];
if (error) {
NSLog(#"%#", [error localizedDescription]);
[[self volumeControl] setEnabled:NO];
[[self playPauseButton] setEnabled:NO];
[[self alertLabel] setText:#"Unable to load file"];
[[self alertLabel] setHidden:NO];
} else {
[[self alertLabel] setText:[NSString stringWithFormat:#"%# has loaded", #"alarm.wav"]];
[[self alertLabel] setHidden:NO];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
//Load the audio into memory
[audioPlayer prepareToPlay];}
And used [audioPlayer play]; to start the sound and to stop I used [audioPlayer stop];. It is working fine when I am on the same ViewController but when I change ViewController [myViewController.audioPlayer stop]; is not working. I am using Storyboard with this.
You can add the stop method in the current class and call that methos in the other class on button click.Please find the code snippet on the following link
Trigger AVAudioPlayer to stop all sounds and play selected except when playing(selected) button is clicked
Adding one more link Why does the AVAudioPlayer stop method not work when switching views
Declare the instance of AVAudioPlayer at .h file as Global.
#property (nonatomic, retain) AVAudioPlayer *theAudio;
You can stop this from another controller
[objViewController.theAudio stop];
This works for me ..Hope it helps you too..
Related
I have saved a recording to my Temp directory and can verify this using iExplorer
The file path structure is TempFolder/UserID/SoundName001.wav
The bit I save to the database is UserID/SoundName001.wav
Here is the code I use to play the file
#property (nonatomic, strong) AVAudioPlayer *player;
-(void) playSound: (NSIndexPath*)recordingIndex {
NSArray *recording = [recordingArray objectAtIndex:recordingIndex.item-1];
NSString *filePath = [NSString stringWithFormat:#"%#%#",NSTemporaryDirectory(),[recording objectAtIndex:2]];
NSURL *recorderURL = [[NSURL alloc] initFileURLWithPath: filePath];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorderURL error:nil];
[self.player prepareToPlay];
[self.player setMeteringEnabled:YES];
[self.player setDelegate:self];
[self.player play];
}
I set a breakpoint and recorderURL returns the following file:///private/var/mobile/Containers/Data/Application/0883D0DC-B1FD-4D06-A7BB-EBD9EEF5D607/tmp/1/Dog001.wav
When I call this method, nothing happens, no crash, no sound...
Am I missing something obvious here?
Did you check the silent switch on your device? I think AVPlayer doesn't play sound if the silent switch is turned on. Try putting this line of code:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
in your viewDidLoad or before [self.player play]; and see if the audio plays.
Whenever I present my scene, I want to start playing a music file and stop the music playing from the last time my scene was presented. I'm trying to do it like this.
[self removeActionForKey:#"Music"];
[self runAction:[SKAction repeatActionForever:[SKAction playSoundFileNamed:#"Music.wav" waitForCompletion:YES]] withKey:#"Music"];
Should I use AVAudioPlayer or [SKAction playSoundFileNamed:]?
Also I would like to know if there is a way to play music file forever in all scenes without starting from the beginning.
To play background music in all scenes I will recommend AVAudioPlayer. You can write the code somewhere in your AppDelegate to access from all the scenes. Here is a sample code to achieve this using AVAudioPlayer
// AVAudioPlayer *bgMusicLoop;
- (void)playBackroundMusic:(NSString *)fileName withExtenstion:(NSString *)fileExtension
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:fileExtension];
NSError *error;
if(bgMusicLoop)
[bgMusicLoop stop];
bgMusicLoop = nil;
bgMusicLoop = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:&error];
if (error) {
NSLog(#"Error in audioPlayer: %#", [error localizedDescription]);
} else {
bgMusicLoop.numberOfLoops = -1;
[bgMusicLoop prepareToPlay];
[bgMusicLoop play];
}
}
- (void)stopBackgroundMusic
{
if(bgMusicLoop)
[bgMusicLoop stop];
bgMusicLoop = nil;
}
- (void)pauseBackgroundMusic
{
if(bgMusicLoop && bgMusicLoop.isPlaying)
[bgMusicLoop pause];
}
- (void)resumeBackgroundMusic
{
if(bgMusicLoop && !bgMusicLoop.isPlaying)
[bgMusicLoop play];
}
For music you should use AVAudioPlayer as using SKAction to play music will block any other actions you might want to run on the scene and its a bit more cumbersome to handle especially if you want to play more sounds along with the music.
Use SKAction to play short sound files (like player jump/fire etc...)
With AVAudioPlayer you can easily set your file to play repeatedly until stopped
I am streaming music file using AVAudioPlayer, It plays fine in background if i use nib file but when i try the same code using storyboard, The music playing stoped. I can't understand the reason why its stop playing in background when i using storyboard.
i am using this code for it
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer setVolume:0.1];
[audioPlayer play];
Can any help me to play it in background using storyboard. Thanks in advance.
Let's try:
#implementation YourViewController
{
AVAudioPlayer *audioPlayer;
}
// if your are using ARC, after exiting this method, system will kill your audioPlayer. This is the reason why you can not play the music.
// in your method:
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
Hi I'm playing the audio file in one view controller when i going the another view controller its still playing the audio how to pause the audio when we going back to another view controller.
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"audio" ofType:#"mp3" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.audioPlayer play];
Please tell where i have to put the pause code for the audio when I'm going for another view controller.
Thanks.
in your viewController dealloc method add code to stop your audioPlayer
- (void)dealloc {
if ([self.audioPlayer isPlaying])
[self.audioPlayer stop];
[super dealloc]; // call if you are not using ARC
}
You can also put the stop audio code in ViewWillDisappear method if you are going deeper into heirarchy
I'm writing an alarm clock app and I need to have the user select the chime to wake up to. I have a UITableView with a list of my sounds and when the user taps a sound I want it to play.
However, my sounds do not play unless I step over the call to AudioServicesPlaySystemSound (or if I put a breakpoint on the call to AudioServicesDisposeSystemSoundID which triggers after I hear the sound).
I had a theory that this was a main thread issue so I used performSelectorOnMainThread:
[self performSelectorOnMainThread:#selector(playWakeUpSound)
withObject:nil
waitUntilDone:true];
but that didn't help. (The value of waitUntilDone doesn't seem to matter.)
This question was promising but I checked and I'm only calling my method once.
This is only a guess, since I don't know what is in playWakeUpSound. If you are using AVAudioPlayer within that call and ARC, it might be because it is getting released. Store the instance of AVAudioPlayer as a member of the class and it should play.
#interface MyClass
{
AVAudioPlayer *player;
}
#end
Then in the implementation:
#implementation MyClass
- (void)playWakeUpSound {
// Assuming name and extension is set somewhere.
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:name ofType:extension]];
NSError* error = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:&error];
if (error) {
NSLog(#"%#", error.localizedDescription);
} else {
[player play];
}
}
#end