我(未成功)尝试使用 AVAudioPlayer 播放存储在 Firebase 中的音频文件。
我收到以下错误消息:创建音频播放器时出错:操作无法完成。 (操作系统状态错误 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")
}
不知道我哪里错了。任何帮助将不胜感激。
您可以尝试使用带有 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()
}
}