【问题标题】:Exception when playing random song from my array list on shake从我的数组列表中播放随机歌曲时出现异常
【发布时间】:2017-12-16 16:00:16
【问题描述】:

我正在开发一个应用程序,它会在设备抖动时播放一首随机歌曲。以下是我的代码

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: UIEventSubtype, with event: UIEvent?) {
        if event?.subtype == UIEventSubtype.motionShake{
            let soundArray=["firstsong","second","fourth"]
            let randomNumber=Int(arc4random_uniform(UInt32(Int32(soundArray.count))))

            let fileLocation = Bundle.main.path(forResource: soundArray[randomNumber], ofType: "mp3")
            do {
                try player=AVAudioPlayer(contentsOf:URL(fileURLWithPath:fileLocation!))
                player.play()
            }catch{

            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

我已将我的 mp3 文件放在音乐文件夹中。 当我摇动设备时,我收到以下错误

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

任何帮助将不胜感激

【问题讨论】:

  • 好的,你需要调试你的代码。用局部变量把它分成小步骤,在函数的顶部设置一个断点,然后单步执行,检查每一行的结果。我的钱在fileLocation!这个表达式上。如果 fileLocation 为 nil,则会崩溃。 (我将 force-unwrap 运算符称为“crash if nil”运算符。在您真正知道自己在做什么之前,您应该避免使用它。)

标签: ios audio shake


【解决方案1】:

等等。你说你把文件放在你的音乐文件夹里?那你的代码是错误的。您发布的代码尝试从您的应用程序包中读取文件。您需要完全使用不同的方法从用户的音乐文件夹中读取文件,并且需要编写该代码来检查文件是否存在,如果不存在则优雅地失败。

我建议将您的声音文件拖到 Xcode 项目中的“resources”文件夹中,并确保选中文件的复选框,以便将它们包含在您的应用程序包中。如果你这样做,你的代码应该可以工作(但你仍然应该检查 nil 而不是使用强制展开,如我上面的评论中所述。)

【讨论】:

  • 请注意,您应该真正使用url(forResource:withExtension:) 而不是path(forResource:ofType:)。 Apple 正在放弃使用路径字符串,并且新开​​发首选基于 URL 的方法。 (在 Mac OS 上,您必须使用基于 URL 的方法才能使沙盒正常工作。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
相关资源
最近更新 更多