出乎意料地发现nil为可选值 - 但是可选值不是nil

时间:2017-10-30 05:30:56

标签: swift optional audiokit

我使用AudioKit设置声音播放器。我的声音引擎设置在具有以下功能的单身中:

override func viewDidLoad() {
    super.viewDidLoad()
    configureAudioPlayer()
}

func configureAudioPlayer() {
    leftPanner = AKPanner(leftOscillator)
    rightPanner = AKPanner(rightOscillator)

    //Set up rain and rainPlayer
    do {
        rain = try AKAudioFile(readFileName: "rain.wav")
        rainPlayer = try AKAudioPlayer(file: rain, looping: true, deferBuffering: false, completionHandler: nil)
    } catch {
        print(error)
    }

    mixer = AKMixer(leftPanner, rightPanner, rainPlayer)
    envelope = AKAmplitudeEnvelope(mixer)

    AudioKit.output = envelope
    AudioKit.start()
}

func startPlaying() {
    leftOscillator.start()
    rightOscillator.start()
    rainPlayer.start() //CRASHES HERE AND SAYS NIL OPTIONAL VALUE
    envelope.start()

    soundIsPlaying = true
}

在一个单独的视图控制器中,我有一个按下按钮时调用以下功能的播放按钮:

let player = AudioPlayer.sharedPlayer

@IBAction func playSound(_ sender: Any) {
    player.leftOscillator.frequency = 220
    player.rightOscillator.frequency = 230

    if player.soundIsPlaying == false {
        player.startPlaying()
    } else {
        player.stopPlaying()
    }
}

当我按下此按钮时,应用程序崩溃并说rainPlayer是零。我做错了吗?当我在configureAudioPlayer()函数中配置它时,为什么rainPlayer会为nil?

更新: 将单例移动到自己的类中,该类继承自NSObject并在其init()函数中调用configureAudioPlayer()解决了我的问题。从未调用viewDidLoad()方法中的configureAudioPlayer()。

0 个答案:

没有答案