AVMusic plays double when switching views - ios

When i switch views the music keep playing the the background what is fine with my app. But when the user comes back to the initial view the music starts again over the original one so the user hears the music double. I have already got some code to check whether the sound is already playing but it doesnt work. :(
Any thoughts?
if (audioPlayer.playing == 0 ) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/CheeZeeLab.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
audioPlayer.volume = 1;
[audioPlayer prepareToPlay];
[audioPlayer stop];
if (audioPlayer == nil)
NSLog(#"werkt niet");
else
[audioPlayer play]; }
else{
}

I bet your problem is in how you transition back to your initial view.
If you're pushing (or doing a segue from the child back to the parent... i.e. a circular segue), you're creating a new instance of your parent view controller.
And creating a new instance starts a fresh version of the audio player playing that sound.
You need to properly pop the view to go back to the previous view controller.

Depending on how you have set up the AVAudioPlayer, with manual setter and getter, with property or even in the constructor. You are confronted with some issues.
When you initialize the ViewController you are allocating an AVAudioPlayer, and if it keeps playing it's not being deallocated, and still retained. And the ViewController won't be deallocated either until every property's retain count is 0.
After going back to the main view, and trying to set up the same ViewController again, my guess is that you are not trying to push the same instance to the stack. But rather making a new instance and pushing that one onto the stack? And that also makes a AVAudioPlayer.
This is ofc a bit of guesswork as a can't see you entire code. But if this is the case, I think you could set things up a bit better. Make sure that the ViewController gets properly deallocated and releasing all it's properties before making a new instance to push to the stack.

Related

Audio overlap issue

I'm developing a iOS app using objective-c. When the application is launched a background music is played. The background music should continue playing when the user clicks help button. Also when the user goes back to the main screen from the help screen the background music should be continuously playing.
For me a new background music is getting played along with the old background music when I navigate from help to main menu. So, I am hearing two background music now.
Could anyone help me in solving this issue?
Regards,
Bharathi.
Your problem could be solved if you retained a reference to your audio player in your UIApplicationDelegate (or some other singleton that's kept around).
//in the .h
#property (nonatomic, strong) AVAudioPlayer *player;
//in the .m
- (void) playMusic
{
if (self.player == nil) {
NSString *path = [NSString stringWithFormat:#"%#/music.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}
if (!self.player.isPlaying) {
[self.player play];
}
}
That way you can call it wherever you need with a:
[(MyAppDelegate*)[UIApplication sharedApplication].delegate playMusic];
Though it might be to your advantage to keep around a SoundsManager class as a singleton in order to handle all the sounds that you'll need to track if you're going to need more than just this one.

How to retain ViewContoller when popped Objective -C

How do you retain a view contoller when its is popped from the stack ?
Basically i have an Mp3 Player view controller. When i'm in that view controller, i can play music. when the music is playing and i navigate to a different controller, The music stops playing, and when i navigate back to that controller, it starts another instance of it. so my guess for a fix, will probably be to retain the view controller ?
This is how i initiate my music player view controller:
NSString *songLargeArtworkURL = [self.songArtworkURL stringByReplacingOccurrencesOfString:#"large" withString:#"crop"];
MusicPlayerViewController *musicPlayer = [[MusicPlayerViewController alloc] init];
musicPlayer.songName = self.testString;
musicPlayer.songArtWork = songLargeArtworkURL;
musicPlayer.songStream = self.songStreamURL;
[self.navigationController pushViewController:musicPlayer animated:YES];
Instead of using a local variable for MusicPlayerViewController, use an instance variable. Only for the first time, allocate the musicPlayer instance. Shown below:
NSString *songLargeArtworkURL = [self.songArtworkURL stringByReplacingOccurrencesOfString:#"large" withString:#"crop"];
if(! musicPlayer) {
musicPlayer = [[MusicPlayerViewController alloc] init];
}
musicPlayer.songName = self.testString;
musicPlayer.songArtWork = songLargeArtworkURL;
musicPlayer.songStream = self.songStreamURL;
[self.navigationController pushViewController:musicPlayer animated:YES];
The above code makes sure that, only for the first time the music player is instantiated. Subsequent times, it pushes the same instance of the music player

ios SystemSound will not respond to volume buttons

Ive used SystemSound in my app in order to play simple sound effects. In addition to this I play a musicvideo through the MPMoviePlayerController - now when I turn the volume up/down the music from the video responds as intended (lowering the volume up/down).
But the system sounds that are played does not respond to the volume. Im playing the system sounds when the user taps certain areas in the app. Heres a snippet of my code for that:
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
SystemSoundID completeSound = nil;
//yellow folder in xcode doesnt need subdirectory param
//blue folder (true folder) will need to use subdirectory:#"dirname"
NSURL *sound_path = [[NSBundle mainBundle] URLForResource: target_sound_filename withExtension: #"wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)sound_path, &completeSound);
AudioServicesPlaySystemSound(completeSound);
}
PS. I doublechecked that my "Settings->Sounds->Ringer and Alerts->Change With Buttons" is set to ON (as I read on some other SO answers that leaving this option OFF will cause systemsound to not respond to the volume buttons)
Further the reason for using systemsound is that it gave the most accurate and responsive results when playing multiple sounds (like in a game).
Id prefer to not use OpenAL if possible (even through 3rd party sound libraries like Finch or CocosDenshion)
Any ideas?
Use the AVAudioPlayer class for playing sounds that are controlled by the user's volume settings (non-system sounds).
You can retain instances of AVAudioPlayer for each sound file that you use regularly and simply call the play method. Use prepareToPlay to preload the buffers.
Cheers to Marcus for suggesting that i could retain instances of AVAudioPlayer for each sound file and use prepareToPlay to preload the sounds. It might be to help for others looking for the same solution so here is how I did it (feel free to comment if anyone have suggestions for improvements)
//top of viewcontroller.m
#property (nonatomic, strong) NSMutableDictionary *audioPlayers;
#synthesize audioPlayers = _audioPlayers;
//on viewDidLoad
self.audioPlayers = [NSMutableDictionary new];
//creating the instances and adding them to the nsmutabledictonary in order to retain them
//soundFile is just a NSString containing the name of the wav file
NSString *soundFile = [[NSBundle mainBundle] pathForResource:s ofType:#"wav"];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile] error:nil];
//audioPlayer.numberOfLoops = -1;
[audioPlayer prepareToPlay];
//add to dictonary with filename (omit extension) as key
[self.audioPlayers setObject:audioPlayer forKey:s];
//then i use the following to play the sound later on (i have it on a tap event)
//get pointer reference to the correct AVAudioPlayer instance for this sound, and play it
AVAudioPlayer *foo = [self.audioPlayers objectForKey:target_sound_filename];
[foo play];
//also im not sure how ARC will treat the strong property, im setting it to nil in dealloc atm.
-(void)dealloc {
self.audioPlayers = nil;
}

AVAudioPlayer in class category with ARC

I'm trying to add a custom click sound on all my buttons in my application. I've created a class category for UIButton with the following code in it:
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle bundleWithIdentifier:#"com.apple.UIKit"] pathForResource:#"Tock" ofType:#"aiff"]];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
if(audioPlayer == nil){
NSLog(#"%#", [error description]);
} else{
[audioPlayer play];
}
All this is executed in: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
But from what I understand there is a common problem with ARC (wich I am using) here. The audioPlayer objects seems to be released before the sound is played. I've also had a look at AudioServicesPlaySystemSound();. But that's no alternative for me at the moment because I need a volume level controller in my application and I've found no way to change the system volume without leaving the app.
My question is: Is there any way to make a strong reference to my audioPlayer object in the UIButton class category? Or is there any other, maybe better way, to get this working?
When adding any object relationship in a category, it's always worth looking at associated objects. Use the objc_setAssociatedObject() and objc_getAssociatedObject() functions. Make sure to use a unique pointer value for the key, and in your case you'll definitely want to use one of the retain association policies to ensure your object's lifespan is appropriate.

AVAUdioPlayer - changing current URL

In my audio player app, if I hit the fast forward button - the player must find the next song in the playlist and play it. What I do is I get the URL from the next song, and try to put it in the background (background is an instance of AVAudioPlayer*) url field, but that property is read only. So what I'm actually doing - I'm calling the initWithContentsOfURL method (again) to set the URL like this :
[self.background initWithContentsOfURL:
[[_playlist.collection objectAtIndex:currentIndex] songURL] error:nil];
Is this legit? I mean, the compiler tells me that the expression result is unused, but it actually works.
Is there another way of doing it? Thanks ;-)
For playing more than one URL, or effectively changing the URL, use the subclass AVQueuePlayer.
AVQueuePlayer is a subclass of AVPlayer you use to play a number of items in sequence.
Example:
NSString *fooVideoPath = [[NSBundle mainBundle] pathForResource:#"tommy" ofType:#"mov"];
NSString *barVideoPath = [[NSBundle mainBundle] pathForResource:#"pamela" ofType:#"mp4"];
AVPlayerItem *fooVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:fooVideoPath]];
AVPlayerItem *barVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:barVideoPath]];
self.queuePlayer = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:fooVideoItem, barVideoItem,nil]];
[self.queuePlayer play];
// things happening...
[self.queuePlayer advanceToNextItem];
Have checked 4 Apple samples, they are using AVAudioPlayer to play one song only. However, your result looks very interesting and impressive! Please let us know, are you stopping the playback before reinitializing object with the same address, are you starting the new audio session ?
As for me, I'd not put the playback and app stability in a risk doing something not mentioned in the documentation but , but to be on the bright side would use the AVAudioPlayer class as it seems the most right, which gives us:
use the error variable to track the possible errors
stop the playing AVAudioPlayer instance, initialize a new instance of AVAudioPlayer and set it to the property letting an old-one to be deallocated automatically.
And you probably know yourself, that
self.background = [self.background initWithContentsOfURL::
will remove the warning for you.

Resources