I’ve got a number of mp3 files in my project bundle and am trying to create an audio player view.
I’ve set a number of breakpoints and error messages for the console, but none of them appear to get triggered. The code seems to run successfully until AFTER the URL and assignment of the AVAudioPlayer objects (not triggering either of the print statements in my error-catching code) and then the app crashes with ‘Fatal error: unexpectedly found nil while unwrapping an optional value’
Here is my code:
import SwiftUI
import AVFoundation
struct AudioPlayerView: View {
@State var audioPlayer = AVAudioPlayer()
var body: some View {
ZStack {
VStack {
Text("Play").font(.system(size: 45)).font(.largeTitle)
HStack {
Spacer()
Button(action: {
self.audioPlayer.play()
}) {
Image(systemName: "play.circle.fill").resizable()
.frame(width: 50, height: 50)
.aspectRatio(contentMode: .fit)
}
Spacer()
Button(action: {
self.audioPlayer.pause()
}) {
Image(systemName: "pause.circle.fill").resizable()
.frame(width: 50, height: 50)
.aspectRatio(contentMode: .fit)
}
Spacer()
}
}
}.onAppear {
initSound()
}
}
func initSound() {
let soundPath = Bundle.main.path(forResource: "cleansing_clearing_breath", ofType: "mp3")
let soundUrl = URL(fileURLWithPath: soundPath!)
if soundUrl != nil {
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundUrl)
} catch {
print("Could not pass file to AVAudioPlayer")
}
} else {
print("Could not create URL object")
return
}
}
}