AVAudioPlayer上客音频,给予现有路径

问题描述 投票:1回答:1

我试图加载音频被设置到viewDidLoad中函数内部不同的按钮。然而,我的应用程序崩溃与此错误:

主题1:致命错误:意外发现零而展开的可选值

override func viewDidLoad() {
    annotateKeys()
    print(constructedArrayOfNotes)


    for key in constructedArrayOfNotes {
        let path = Bundle.main.path(forResource: key, ofType: "mp3")
        do {
            try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
            player.prepareToPlay()
            audioPlayers.append(player)
        } catch {
            print("error")
        }

    }

的注释功能构建constructedArrayOfNotes阵列。

音频文件的名称是“PIANO_C3.mp3”。

这是annotateKeys功能

func annotateKeys() {
    for index in 0...11 {
        constructedArrayOfNotes[index] = "PIANO_" + arrayOfNotes[index] + String(leftSideOfPiano)
    }
    for index in 12...23 {
        constructedArrayOfNotes[index] = "PIANO_" + arrayOfNotes[index] + String(rightSideOfPiano)
    }
}

这是音频文件的样子:

enter image description here

我不知道到底是什么,我做错了,但我猜的路径或者是不正确或Xcode中无法找到的音频文件。

任何帮助,将不胜感激。

这是更多的代码:

var audioPlayers = [AVAudioPlayer]()

var player = AVAudioPlayer()




// An array with notes C through B is sequenced twice in order to
// traverse the left and right keyboard.
let arrayOfNotes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]

var constructedArrayOfNotes = ["","","","","","","","","","","","","","","","","","","","","","","",""]
ios swift xcode avaudioplayer
1个回答
0
投票

这是因为path将是零在某些时候,这意味着你的密钥设置不正确。这种替换你的函数

 for key in constructedArrayOfNotes {
        if let path = Bundle.main.path(forResource: key, ofType: "mp3") {
        do {
            try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            player.prepareToPlay()
            audioPlayers.append(player)
        } catch {
            print("error")
        }
      }
    }

看看哪些关键是不是在玩。

© www.soinside.com 2019 - 2024. All rights reserved.