简体   繁体   English

如何处理AVAudioPlayer在Swift中是可选的?

[英]How to handle AVAudioPlayer being an optional in Swift?

I have a controller that may or may not play audio on viewdidload and therefore need to stop the audio from playing on viewwilldisappear. 我有一个控制器,它可能无法在viewdidload上播放音频,因此需要停止在viewdidload上播放音频。

It seems this sample code doesn't work if no audio is playing (crashes on .playing) because the audioPlayer isn't nil, but also hasn't been properly init'd (and doesn't need to be because there will be no audio) 如果没有音频正在播放(.playing崩溃),则此示例代码似乎不起作用,因为audioPlayer不是nil,但是还没有正确初始化(并且不需要,因为会存在没有声音)

var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    if let uwStoryAudio = story.audioFile {
        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: uwStoryAudio, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
}

override func viewWillDisappear(animated: Bool) {
    if audioPlayer.playing //CRASH
    {
        audioPlayer.stop()
    }
}

This is what I've currently got, using an Optional but I don't think it's "correct" / best practice... 这是我目前使用的Optional,但我认为这不是“正确” /最佳实践...

var audioPlayer: AVAudioPlayer?

override func viewDidLoad() {
    if let uwStoryAudio = uwStory.audioFile {
        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: uwStoryAudio, error: &error)
        audioPlayer!.prepareToPlay()
        audioPlayer!.play()
    }
}

override func viewWillDisappear(animated: Bool) {
    if let uwAudioPlayer = audioPlayer
    {
        uwAudioPlayer.stop()
    }
}

Is there a better way of doing this? 有更好的方法吗?

No, that's it. 不,就是这样。 Why do you think it's wrong? 您为什么认为这是错误的? The optional says it may be nil, so you need to check for nil - which you are doing correctly. 可选参数说它可能为nil,因此您需要检查nil-您做得正确。

Also, add in the playing check like this: 另外,像这样添加播放检查:

if let uwAudioPlayer = self.audioPlayer {
    if uwAudioPlayer.playing { etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM