暂停并使用AVAudioSession播放音频
我有1个控制器。首先我开始播放audio1。我使用此代码:暂停并使用AVAudioSession播放音频
- (void)viewDidLoad
{
//code to not turn off audio with using mute switch
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: NO error: nil];
//code to play audio
NSString *soundFilePath = [NSString stringWithFormat:@"%@/%@.mp3",[[NSBundle mainBundle] resourcePath], @"sound"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
_player.numberOfLoops = -1;
[_player play];
}
但是,当我隐藏我的应用程序音频没有暂停。当我隐藏我的应用程序并在应用程序到达前台时暂停点播放时,我想暂停音频。怎么做?
你可以使用通知检测应用程序将背景/前景。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground:) name:@"enterBackGroundNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForeground:) name:@"enterForeGroundNotification" object:nil];
- (void)appEnterBackground:(NSNotification *) notification {
[_player pause];
}
- (void)appEnterForeground:(NSNotification *) notification {
[_player play];
}
在下一个控制器中,我使用AVAudioSession,并且在此控制器中,如果隐藏应用程序,音频不应该停止。但是,如果我在下一个控制器中使用您的代码并隐藏应用程序(当下一个控制器中的音频播放并且第一个控制器暂停时)并打开第一个控制器的音频将与第二个控制器的音频一起播放 – user
为此,您需要为应用程序在后台和前台添加通知。
申报玩家第一
AVAudioPlayer *player;
在viewDidLoad中
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackgroundActive:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForegroundActive:) name:UIApplicationWillEnterForegroundNotification object:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: NO error: nil];
//code to play audio
NSString *soundFilePath = [NSString stringWithFormat:@"%@/%@.mp3",[[NSBundle mainBundle] resourcePath], @"alarm_tone"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1;
[player play];
添加该代码添加输入后台方法。
-(void)appEnterBackgroundActive:(NSNotification*)note
{
[player pause];
}
添加输入前台方法。
-(void)appEnterForegroundActive:(NSNotification*)note
{
[player play];
}
在下一个控制器中,我使用AVAudioSession,控制器音频不应该停止如果隐藏应用程序但是,如果我在下一个控制器中使用您的代码并隐藏应用程序(当下一个控制器中的音频播放时,第一个控制器中的音频暂停时),并且从第一个控制器打开音频将与第二个控制器 – user
的可能的复制[播放/用相同的按钮\暂停[AVAudioPlayer \]](https://stackoverflow.com/questions/6635604/play-pause-with-the-same-button-avaudioplayer) – kb920