我相信大家可能已经将AVFoundation添加到“项目常规信息”选项卡的框架列表中。
错误代码如下:
import SwiftUI
import AVFoundation
struct PlayerDetailView: View {
@State private var downloadedFilePath: URL = nil
var audioPlayer: AVAudioPlayer
var body: some View {
在我将var audioPlayer: AVAudioPlayer
声明移到import AVFoundation
它似乎正在起作用。
因此,以下代码在一个SwiftUI
项目中为我工作。
import SwiftUI
import AVFoundation
var audioPlayer: AVAudioPlayer!
struct PlayerDetailView: View {
@State private var downloadedFilePath: URL = nil
var body: some View {
VStack {
Button("Play the Downloaded Track") {
if let downloadedPath = self.downloadedFilePath?.path, FileManager().fileExists(atPath: downloadedPath) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: self.downloadedFilePath!)
guard let player = audioPlayer else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
} else {
print("The file doesn not exist at path || may not have been downloaded yet")
}
}
}
}
}
我最初遵循的是本教程 CodeWithChris的,其讨论也导致了上述变化。还结帐以下教程太多,如果你需要进一步的例子。
希望这会对您中的某人有所帮助!
干杯!