我是Swift的新手,我设法从firebase下载音频并将其存储在本地,但不知道如何使用AVAudioPlayer。任何帮助,将不胜感激。这是我到目前为止所得到的。
class FireBaseViewController: UIViewController {
var audioPlayer:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let storageRef = FIRStorage.storage().reference()
let files = storageRef.child("Audio/Self Commitment.m4a")
let localURL: NSURL! = NSURL(fileURLWithPath:"/Users/wayne/Desktop/Playground/Audio/Self Commitment.m4a")
let downloadTask = files.write(toFile: localURL as URL) { (URL, error) -> Void in
if (error != nil) {
print("Uh-oh, an error occurred!")
} else {
print("Local file URL for is returned")
}
}
let audioPath = localURL
do {
try audioPlayer = AVAudioPlayer(contentsOf:URL(fileURLWithPath: audioPath))
} catch {print("file is unavilable")
}
audioPlayer.play()
}
}
我有同样的问题。我所做的是使用FileManager生成我将存储文件的URL
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("file_name.mp3")
然后你可以保存文件并像这样播放:
storeRef.getData(maxSize: 10 * 1024 * 1024) { (data, error) in
if let error = error {
print(error)
} else {
if let d = data {
do {
try d.write(to: fileURL)
self.audioPlayer = try AVAudioPlayer(contentsOf: fileURL)
self.audioPlayer.play()
} catch {
print(error)
}
}
}
}
我已经尝试过了,它有效!
您也可以播放音频而无需下载。要做到这一点,你应该:
1)获取下载URL
2)使用此URL启动AVPlayerItem
3)设置播放器和播放
Swift 4.2
let storage = Storage.storage()
let storageReference = storage.reference(forURL: storagePath)
storageReference.downloadURL { (hardUrl, error) in
if error == nil, let url = hardUrl {
self.playerItem = AVPlayerItem(url: url)
self.playerInstance = AVPlayer(playerItem: self.playerItem)