提问人:Booysenberry 提问时间:11/15/2023 更新时间:11/15/2023 访问量:36
从Firebase播放音频文件不起作用
Playing audio file from Firebase not working
问:
我(未成功)尝试使用 AVAudioPlayer 播放存储在 Firebase 中的音频文件。
我收到以下错误消息:创建音频播放器时出错:无法完成操作。(OSStatus 错误2003334207。
下面是我的音频播放器视图模型的代码:
class AudioPlayerViewModel: ObservableObject {
private var audioPlayer: AVAudioPlayer?
func playAudioFromUrl(from storagePath: String) {
let storage = Storage.storage()
let storageRef = storage.reference()
let audioRef = storageRef.child(storagePath)
audioRef.downloadURL { url, error in
print(audioRef)
guard let audioURL = url, error == nil else {
print("Error fetching audio URL: \(error?.localizedDescription ?? "")")
return
}
print("Audio URL: \(audioURL)")
print("Audio URL String: \(audioURL.absoluteString)")
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
} catch {
print("Error creating audio player: \(error.localizedDescription)")
if let nsError = error as NSError? {
print("Error code: \(nsError.code)")
}
}
}
}
func stopAudio() {
audioPlayer?.stop()
}
}
我的观点代码:
struct PlaybackControlsView: View {
var audioPath: String
@ObservedObject private var audioPlayerVM = AudioPlayerViewModel()
var body: some View {
VStack {
// Add UI elements here, e.g., play and stop buttons
Button("Play Audio") {
audioPlayerVM.playAudioFromUrl(from: "Stories/\(audioPath).mp3")
}
.padding()
Button("Stop Audio") {
audioPlayerVM.stopAudio()
}
.padding()
}
}
}
#Preview {
PlaybackControlsView(audioPath: "example")
}
不知道我在这里哪里出了问题。任何帮助将不胜感激。
答:
1赞
workingdog support Ukraine
11/15/2023
#1
您可以尝试使用带有 url 而不是
这似乎只播放来自文件或缓冲区的音频数据。AVPlayer
AVAudioPlayer
class AudioPlayerViewModel2: ObservableObject {
private var audioPlayer: AVPlayer? // <-- here
func playAudioFromUrl(from storagePath: String) {
let storage = Storage.storage()
let storageRef = storage.reference()
let audioRef = storageRef.child(storagePath)
audioRef.downloadURL { url, error in
print(audioRef)
guard let audioURL = url, error == nil else {
print("Error fetching audio URL: \(error?.localizedDescription ?? "")")
return
}
print("Audio URL: \(audioURL)")
print("Audio URL String: \(audioURL.absoluteString)")
// --- here
let playerItem = AVPlayerItem(url: audioURL)
self.audioPlayer = AVPlayer(playerItem: playerItem)
self.audioPlayer?.volume = 10
self.audioPlayer?.play()
}
}
func stopAudio() {
audioPlayer?.pause()
}
}
上一个:UILabel 截断
评论
@StateObject private var audioPlayerVM = AudioPlayerViewModel()
audioURL