-1

我在我的代码中遇到了这个问题:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

此消息出现在我的代码的这一行:

try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))

任何帮助将不胜感激。提前致谢!

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {

        if event?.subtype == UIEvent.EventSubtype.motionShake {

            let fileLocation = Bundle.main.path(forResource: "sound1", ofType: "mp3")

            do {
                try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
                player.play()
            } catch {
                // process error   
            }   
        }   
    }
}
4

1 回答 1

0

未找到您的文件。

我做了一些小改动来帮助调试和防止崩溃。

import UIKit
import AVKit

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {

        if event?.subtype == UIEvent.EventSubtype.motionShake {
            if let fileLocation = Bundle.main.path(forResource: "sound1", ofType: "mp3") {
                do {
                    let player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation))
                    player.play()
                } catch (_) {
                    print("AVAudioPlayer could not play the file.")
                }
            } else {
                print("File was not be found.")
            }
        }
    }
}
于 2019-01-31T18:47:30.063 回答