swift 需要帮助一个声音迅速[重复]

ecfdbz9o  于 2023-03-28  发布在  Swift
关注(0)|答案(1)|浏览(159)

此问题在此处已有答案

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?(16个答案)
5天前关闭.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!

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

    @IBAction func keyPressed(_ sender: UIButton) {
            
        playSound(soundName: sender.currentTitle!)
        
        sender.alpha = 0.5
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            sender.alpha = 1.0
        }
      
    }
    
    func playSound(soundName: String) {
        let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
        player = try!
        
        AVAudioPlayer(contentsOf: url!)
        player.play()
        
    }
}

我正在创建一个钢琴应用程序,它运行,但当我点击一个键时,它崩溃并给我这个错误:
Piano_App/ViewController.swift:36:致命错误:打开可选值时意外发现nil 2023-03-22 19:59:02.100302-0700 Piano App[41562:2080588] Piano_App/ViewController.swift:36:致命错误:展开可选值时意外发现nil
我还在学习Swift,所以任何帮助都非常感谢!

wljmcqd8

wljmcqd81#

  • 尽量不要隐式地展开你的player变量。
  • 使用guard let打开可选的url变量。

解决该问题的可能方案,

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer?

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

    @IBAction func keyPressed(_ sender: UIButton) {
            
        playSound(soundName: sender.currentTitle!)
        
        sender.alpha = 0.5
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            sender.alpha = 1.0
        }
      
    }
    
    func playSound(soundName: String) {
        guard let url = Bundle.main.url(forResource: soundName, withExtension: "wav") else {
            print("Error: sound file not found")
            return
        }

do {
        player = try AVAudioPlayer(contentsOf: url)
        player?.play()
    } catch let error {
        print("Error: \(error.localizedDescription)")
    }
}
}

相关问题