0

I am creating this app were there is background music playing, but I want it so the user can stop the music with a UISwitch if they dont want background music. I already have the code working for the music to play and stop (Code below) with the switch bu my question is this. When i switch to a different view (one that the switch isnt on) and the music is playing, then go back to the view. The switch is off, when i turn it back on (even thought the music is already playing), it will play it again and they will overlap each other (same music file).

Code for the switch and music player...

-(IBAction)play:(id)sender {
if (audioControlSwitch.on) {

[sound setTextColor:[UIColor blueColor]];
[sound setText:@"Sound On"];

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Tone 2.m4a", [[NSBundle mainBundle] resourcePath]]];

NSError *error;
audioPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer1.numberOfLoops = 100000000000000000;

[audioPlayer1 play];
} else {

[sound setTextColor:[UIColor darkGrayColor]];
[sound setText:@"Sound Off"];

[audioPlayer1 stop];

}

}
Kyle Greenlaw
  • 737
  • 1
  • 8
  • 20

1 Answers1

0

in yourViewController.h

@interface yourViewController : NSObject <AVAudioPlayerDelegate> { 
    BOOL    inBackground;
}

- (void)registerForBackgroundNotifications;

in yourViewController.m

@synthesize inBackground;

#pragma mark background notifications
- (void)registerForBackgroundNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(setInBackgroundFlag)
                                             name:UIApplicationWillResignActiveNotification
                                           object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(clearInBackgroundFlag)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];
}

- (void)setInBackgroundFlag
{
    inBackground = true;
}

- (void)clearInBackgroundFlag
{
    inBackground = false;
}

- (void)updateViewForPlayerStateInBackground:(AVAudioPlayer *)p
{
    if (p.playing)
    {
    // Do something
    }
    else
    {
    // Do something else
    }
}

#pragma mark AVAudioPlayer delegate methods
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)p successfully:(BOOL)flag
{
    if (flag == NO)
    NSLog(@"Playback finished unsuccessfully");
        [p setCurrentTime:0.];
if (inBackground)
{
        [self updateViewForPlayerStateInBackground:p];
}
else
{
}
}

- (void)playerDecodeErrorDidOccur:(AVAudioPlayer *)p error:(NSError *)error
{
NSLog(@"ERROR IN DECODE: %@\n", error);
}

// we will only get these notifications if playback was interrupted
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)p
{
    NSLog(@"Interruption begin. Updating UI for new state");
    // the object has already been paused,  we just need to update UI
    if (inBackground)
    {
         [self updateViewForPlayerStateInBackground:p];
    }
    else
    {
    }
}

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)p
{
NSLog(@"Interruption ended. Resuming playback");
[self startPlaybackForPlayer:p];
}

-(void)startPlaybackForPlayer:(AVAudioPlayer*)p
{
if ([p play])
{

}
else
    NSLog(@"Could not play %@\n", p.url);
}

@end
  • Observe when your app enter/exit background - update boolean - use boolean where you want. AVAudioPlayerDelegate give you access to interruptions, finish and errors for example with "audioPlayer1". audioControlSwitch.on/off should be inside "updateViewForPlayerStateInBackground" –  May 23 '13 at 15:00
  • Sorry but i am new to the coding world, any way you could explain this easier for me? – Kyle Greenlaw May 23 '13 at 19:01
  • 1
    Make search : "avaudioplayer" and "avaudiosession" There are some links : http://stackoverflow.com/questions/4771105/how-do-i-get-my-avplayer-to-play-while-app-is-in-background http://developer.apple.com/library/ios/#samplecode/avTouch/Listings/Classes_avTouchController_mm.html <-- I based my code on it. http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/UsingAudio.html#//apple_ref/doc/uid/TP40009767-CH2 http://developer.apple.com/library/ios/#documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Cookbook/Cookbook.html –  May 23 '13 at 22:17