当屏幕快速关闭时,IOS Audio停止播放

时间:2015-04-08 06:06:30

标签: ios iphone swift avaudioplayer

你是IOS和Swift的新手。

我正在创建一个包含两个音频文件的应用,这些文件在第二个ViewController上播放。我使用导航控制器和push转到第二个ViewController。正如我在回到第一个ViewController时发现的那样,音频不会停止,我使用了这段代码:

override func viewWillDisappear(animated: Bool) {
    audioPlaying.stop()
}

现在音频在返回时停止,但是如果屏幕熄灭,音频将停止意味着当应用程序被锁定或在后台时, 我怎么能摆脱这个?

更多代码:

var audioPlaying = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    audioPlaying = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audioOne", ofType: "mp3")!), error: nil)
}

override func viewWillDisappear(animated: Bool) {
        audioPlaying.stop()
}
@IBAction func playPause(sender: AnyObject) {
    if buttonLabelChange == true {
        let image = UIImage(named: "btn_pause.png") as UIImage?
        playPauseButton.setBackgroundImage(image, forState: UIControlState.Normal)
        buttonLabelChange = false
        audioPlaying.play()
    }else{
        let image = UIImage(named: "btn_play.png") as UIImage?
        playPauseButton.setBackgroundImage(image, forState: UIControlState.Normal)
        buttonLabelChange = true
        audioPlaying.stop()
    }
}

@IBAction func sliderAction(sender: AnyObject) {
    audioPlaying.stop()
    audioPlaying.currentTime = NSTimeInterval(sliderOutlet.value)
    audioPlaying.prepareToPlay()
    audioPlaying.play()
    let image = UIImage(named: "btn_pause.png") as UIImage?
    playPauseButton.setBackgroundImage(image, forState: UIControlState.Normal)
    buttonLabelChange = false
}

4 个答案:

答案 0 :(得分:1)

您是否尝试过使用isMovingFromParentViewController方法?

该方法在弹出视图时返回true,但在手机锁定时返回false

override func viewWillDisappear(animated: Bool) {

        if self.isMovingFromParentViewController()
        {
                audioPlaying.stop()
        }
}

答案 1 :(得分:0)

尝试在deinit方法中使用它。希望这可以帮助!!

deinit {

    if (audioPlayer.playing){
    audioPlayer.stop();
    }
}

答案 2 :(得分:0)

在您的视图中执行一项注册applicationWillResignActive的通知,当应用程序被锁定时,它会进入该方法,并停止音频播放器。

1)将此代码放在viewDidLoad()

   NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" ofType:@"mp3"]];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [audioPlayer play];

答案 3 :(得分:0)

删除默认导航后退按钮添加自定义按钮并执行操作。

//隐藏导航栏 - 在viewdidload(FirstViewController)中添加此代码

self.navigationController?.navigationBarHidden = true;

第二个视图控制器中的

@IBAction func popView(sender:AnyObject)     {

   audioPlaying.stop()
    self.navigationController?.popViewControllerAnimated(true);

}