检测音乐是否正在播放,并打开或关闭开关



我正在创建这个应用程序有背景音乐播放,但我希望它,所以用户可以停止音乐与一个UISwitch,如果他们不想要背景音乐。我已经有代码工作的音乐播放和停止(代码下面)与开关,但我的问题是这样的。当我切换到另一个视图时(开关没有打开),音乐正在播放,然后回到视图。开关是关闭的,当我把它打开时(即使音乐已经在播放),它会再次播放,它们会相互重叠(相同的音乐文件)。

开关和音乐播放器代码…

-(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];
}
}

in yourViewController.h

@interface yourViewController : NSObject <AVAudioPlayerDelegate> { 
    BOOL    inBackground;
}
- (void)registerForBackgroundNotifications;
在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

最新更新