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

5 iphone avaudioplayer ios swift

嗨,我是IOS和Swift的新手.

我正在制作一个包含两个音频文件的应用程序,它们在第二个播放ViewController.我使用导航控制器,然后push转到第二个ViewController.正如我在回到第一个时发现的那样ViewController,音频不会停止,我使用了这段代码:

override func viewWillDisappear(animated: Bool) {
    audioPlaying.stop()
}
Run Code Online (Sandbox Code Playgroud)

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

更多代码:

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
}
Run Code Online (Sandbox Code Playgroud)

Dej*_*dar 1

您尝试过使用该方法吗isMovingFromParentViewController

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

override func viewWillDisappear(animated: Bool) {

        if self.isMovingFromParentViewController()
        {
                audioPlaying.stop()
        }
}
Run Code Online (Sandbox Code Playgroud)