给定现有路径的 AVAudioPlayer 大量加载音频

Posted

技术标签:

【中文标题】给定现有路径的 AVAudioPlayer 大量加载音频【英文标题】:AVAudioPlayer lot loading audio, given existing path 【发布时间】:2017-11-12 04:34:06 【问题描述】:

我正在尝试将要设置的音频加载到 viewDidLoad 函数内的不同按钮。但是,我的应用程序因此错误而崩溃:

线程 1:致命错误:打开包装时意外发现 nil 可选值

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")
        

    

annotate函数构造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)
    

这是音频文件的样子:

我不确定我做错了什么,但我猜路径不正确或 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 = ["","","","","","","","","","","","","","","","","","","","","","","",""]

【问题讨论】:

【参考方案1】:

那是因为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")
        
      
    

看看哪个键没有弹奏。

【讨论】:

我试过了,但结果是一个空的 audioPlayers 数组。 你的 arrayOfNotesleftSideOfPiano / rightSideOfPiano 是什么 两边是当前钢琴八度 粘贴更多代码并发布这些文件的屏幕截图以查看其名称 很明显路径不正确,这就是为什么你得到一个空的audioPlayers 数组。您是否尝试在追加之前播放每个声音?

以上是关于给定现有路径的 AVAudioPlayer 大量加载音频的主要内容,如果未能解决你的问题,请参考以下文章

AVAudioPlayer 播放大量音频文件后停止播放:kAudio_TooManyFilesOpenError

一次打开大量的AVAudioPlayers?

播放 AVAudioPlayer 时游戏卡顿

iOS 在特定时间停止音频播放(AVAudioPlayer 结束时间)

使用 libexif 和 libjpeg 在现有 JPEG 上设置 exif 标签

从 plist(NSArray) 中挑选歌曲并使用 AVAudioPlayer 播放?