I believe you all might have added the AVFoundation
to the frameworks list in Project General Info tab.
Erroneous Code was as follows:
import SwiftUI
import AVFoundation
struct PlayerDetailView: View {
@State private var downloadedFilePath: URL = nil
var audioPlayer: AVAudioPlayer
var body: some View {
And after I moved the var audioPlayer: AVAudioPlayer
declaration to just after the line of import AVFoundation
line it seemed to be working.
So following code worked for me in a SwiftUI
project:
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")
}
}
}
}
}
I was initially following this tutorial of CodeWithChris and its discussion also led to above change. Also checkout following tutorial too if you need further examples.
Hope this will be helpful to someone of you out there!
Cheers!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…