AVAudioFile中的URL为nil

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

我正在尝试使用AVAudioEngine在背景音频文件上播放多个音频文件。当我尝试初始化backgroundAudioFile时,应用程序崩溃说:Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=com.apple.coreaudio.avfaudio Code=2003334207 "(null)" UserInfo={failed call=ExtAudioFileOpenURL((CFURLRef)fileURL, &_extAudioFile)}.

传递给初始值设定项的URL有效。打印出来。

import Foundation
import AVFoundation

class AudioPlayer {

  var timeIndex = 0 // keeps track of the index of the item transveersed within `timesToTransverse` by `player?.addBoundaryTimeObserver`


var topAudioFiles: [AVAudioFile] = []
var engine:AVAudioEngine
var backgroundAudioNode: AVAudioPlayerNode
var backgroundAudioFile: AVAudioFile
var topAudioAudioNodes = [AVAudioPlayerNode]()
var mixer: AVAudioMixerNode
var timer: Timer!
var urls: [URL] = []
var player: AVPlayer!
var timesToTransverse = [NSValue]() //contains timeValues in seconds such as ["1.54",2.64, 67.20]
var delays = [UInt64]()

fileprivate var timeObserverToken: Any?

init (url: URL, urls: [URL] = [], timesToTransverse: [NSValue]) {

    self.urls = urls
    self.timesToTransverse = timesToTransverse
    topAudioFiles = urls.map { try! AVAudioFile(forReading: $0) }

   print("the remote url is \(url)")
 // it prints the url is https://firebasestorage.googleapis.com/v0/b/salsaworld-658f3.appspot.com/o/adminAudioFiles%2F-LWv5rnKiLawXvsSsQgG.m4a?alt=media&token=19e8eac0-2b47-49e2-acd3-9a459903f84b

    //it crashes on this line
    backgroundAudioFile = try! AVAudioFile(forReading: url)


    player = AVPlayer(url: url)
    engine = AVAudioEngine()
    mixer = AVAudioMixerNode()

    engine.attach(mixer)
    engine.connect(mixer, to: engine.outputNode, format: nil)
    backgroundAudioNode = AVAudioPlayerNode()

    initTopAudioNodes()
    try! engine.start()
}


func initTopAudioNodes() {
    for _ in topAudioFiles {
        topAudioAudioNodes += [AVAudioPlayerNode()]
    }

    for node in topAudioAudioNodes {
        engine.attach(node)
        engine.connect(node, to: mixer, format: nil)
     }
 }//end initTopAudioNodes


 func playWithAudioPlayerAndNodes() {
    player.play()
    var i = 1

  timeObserverToken =  player.addBoundaryTimeObserver(forTimes: timesToTransverse, queue: nil) {
    [weak self] in

    guard let self = self else {return}

        let index = i % self.topAudioAudioNodes.count
        let node = self.topAudioAudioNodes[index]
        node.scheduleFile(self.topAudioFiles[index], at: nil, completionHandler: nil)
        node.play()
        i += 1

    /* Because there are no time signature changes, 
     we can simply increment  timeIndex with + 1 every time 
    `addBoundaryTimeObserver`'s completion handler is called. 
    Then, we subscript timesToTransverse with timeIndex 
    in order to get the subsequent timeInSeconds
   */
    guard self.timeIndex < self.timesToTransverse.count else {return}
    print("timeIndex is now \(self.timeIndex)")

    let timeElement = self.timesToTransverse[self.timeIndex]
    let timeInSeconds = CMTimeGetSeconds(timeElement.timeValue)

   //use reminder operator to determine the beat count
     let beat = (self.timeIndex + 1) % 8 == 0 ? 8 : ((self.timeIndex + 1) % 8)
    print("Beat would be: ", beat)

   /*
     0: (0 + 1) % 8 = 1
     1: (1 + 1) % 8 = 2
     6: (6 + 1) % 8 = 7
     7: (7 + 1) % 8 = 0
     */

    self.timeIndex += 1

}//end class AudioPlayer




  // create instance of class AudioPlayer and call func playWithAudioPlayerAndNodes



   class HomeViewController {

      override func viewDidLoad() {
        super.viewDidLoad()

       let bundle = Bundle.main
       let one = bundle.url(forResource: "1", withExtension: "wav")!
       let two = bundle.url(forResource: "2", withExtension: "wav")!
       let three = bundle.url(forResource: "3", withExtension: "wav")!
       let five = bundle.url(forResource: "5", withExtension: "wav")!
       let six = bundle.url(forResource: "6", withExtension: "wav")!
       let seven = bundle.url(forResource: "7", withExtension: "wav")!

       // mediaArray contains string URL's downloaded from FirebaseDatabse
       let mediaItem = mediaArray[tableIndexPath.row]
        guard let backgroundAudio = URL(string: mediaItem.mediaAudioUrlStringRepresentation ?? "") else {return}

    let audioPlayer = AudioPlayer(url:
    backgroundAudio,
    urls: [one, two, three, five, six, seven],
    timesToTransverse: timesToTransverse)

     //start playing
    audioPlayer.playWithAudioPlayerAndNodes()
      }
  }
swift avaudioplayer avaudioengine
1个回答
0
投票

你不能在远程文件上调用AVAudioFile(forReading:)。您需要下载二进制数据并使用audio file stream services将其解析为数据包。这样,您可以将数据包提供给缓冲区,并通过音频引擎从缓冲区播放。

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