【问题标题】:Audio Stream via firebase通过 Firebase 的音频流
【发布时间】:2017-07-03 08:54:19
【问题描述】:

我已经直接在firebase Storage中上传了一些歌曲,我只想在AVAudioPlayer中播放歌曲。 以下是我正在尝试的代码:

var mainRef: FIRStorageReference {
    return FIRStorage.storage().reference(forURL: "gs://musicapp-d840c.appspot.com")
}

var audioStorageRef: FIRStorageReference{
    return mainRef.child("SongsPath")
}

audioStorageRef.downloadURL { url, error in

    if let error = error {
        print(error.localizedDescription)
    } else {

        if let url = url {

            do {
                self.audioPlayer = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: String(describing: url)) as URL)
                self.audioPlayer.play()
            } catch  {}

            let storyboard  = UIStoryboard(name: "AudioPlayer", bundle: nil)
            let audioVc = storyboard.instantiateViewController(withIdentifier: "AudioPlayerViewController") as! AudioPlayerViewController
            audioVc.playThisSong = String(describing: url)

            self.present(audioVc, animated: false, completion: nil)
        }
    }
}

这里来自firebase 的歌曲网址正在传递,但它正在跳过self.audioPlayer.play。 ,我只想流式传输音频。我可以为此找到适当的解决方案吗?

【问题讨论】:

    标签: ios swift firebase firebase-storage


    【解决方案1】:

    这不是流式传输的答案。

    这是下载文件,将其存储在本地,并在文件完成下载后播放音频的答案。

    使用带文件扩展名的路径字符串获取 Firebase 存储引用。使用我们用于 Firebase 存储引用的相同路径字符串获取文件 url 以将其存储在设备上。

    使用 write(toFile: URL) 启动下载任务。将下载任务存储在变量中以添加观察者。下载成功后,播放音频。

    在 Swift 4 中:

    var player: AVAudioPlayer?
    
    let pathString = "SongsPath.mp3"
    let storageReference = Storage.storage().reference().child(pathString)
    let fileUrls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    
    guard let fileUrl = fileUrls.first?.appendingPathComponent(pathString) else {
        return
    }
    
    let downloadTask = storageReference.write(toFile: fileUrl)
    
    downloadTask.observe(.success) { _ in
        do {
            self.player = try AVAudioPlayer(contentsOf: fileUrl)
            self.player?.prepareToPlay()
            self.player?.play()
        } catch let error {
            print(error.localizedDescription)
        }
    }
    

    这是最少的代码。实施您认为合适的错误处理。

    Firebase example of downloading locally

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 2012-01-27
      • 2013-06-07
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      相关资源
      最近更新 更多