0

我创建了一个数组,它是我的集合视图的数据。我正在尝试点击 CollectionViewCell 并播放包含在我的数组的文件组件中的声音。我不知道如何播放声音,甚至无法开始,因为我的 xcode 项目中的文件为空值。

错误:线程 1:致命错误:在展开可选值时意外发现 nil

如果我不强制打开文件,它会给我一个错误......

class ViewController: UIViewController {

let sounds : [Sounds] = [Sounds(statement: "A", file: Bundle.main.url(forResource: "A", withExtension: "aifc")!),
                            Sounds(statement: "B", file: Bundle.main.url(forResource: "B", withExtension: "aifc")!),
                            Sounds(statement: "C", file: Bundle.main.url(forResource: "C", withExtension: "aifc")!),
                            Sounds(statement: "D", file: Bundle.main.url(forResource: "D", withExtension: "aifc")!)]

}

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sounds.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "soundCell", for: indexPath) as! CollectionViewCell
        let Soundz = sounds[indexPath.item]
        cell.cellLabel.text = Soundz.statement

        return cell
    }

}

struct Sounds{
    var statement : String
    var file : URL 
}

4

3 回答 3

1

看起来您的文件未附加到项目中。检查附加文件的捆绑资源和目标。在这种情况下,最好使用“lazy var”而不是“let”

于 2019-04-01T10:24:54.160 回答
0

首先,!当您尝试获取文件的 URL 时,不应在声音数组中强制解包。这是导致崩溃的原因。您应该选择一个可选的 URL。

struct Sounds{
    var statement : String
    var file : URL?
}


let sounds : [Sounds] = [Sounds(statement: "A", file: Bundle.main.url(forResource: "A", withExtension: "aifc")),
                            Sounds(statement: "B", file: Bundle.main.url(forResource: "B", withExtension: "aifc")),
                            Sounds(statement: "C", file: Bundle.main.url(forResource: "C", withExtension: "aifc")),
                            Sounds(statement: "D", file: Bundle.main.url(forResource: "D", withExtension: "aifc"))]

}

这将首先解决崩溃。当您访问要播放的文件时,只需先检查 URL 是否存在或为零。

其次,确保将所有声音文件添加到 Target。检查文件的属性检查器并确保选中您的应用程序目标复选框。

于 2019-04-01T10:21:36.813 回答
0

不要将 Bundle.main.url(forResource: "", withExtension: "") 保留在 Array 中,好像 Array 大小会增加一样,该语句会占用大量内存。

而不是您的方法,将fileName保留在您的对象中,当您需要该文件的路径时,只需调用对象的 filePath 实例变量。

 let sounds = [Sounds(statement: "A", fileName: "A")]

您的结构将如下所示

struct Sounds {
    var statement : String
    var fileName: String
    var filePath : URL? {
        return Bundle.main.url(forResource: fileName, withExtension: "html")
    }
}

希望这会帮助你。

于 2019-04-01T10:49:32.853 回答