If have tinkered with Swift AVAudioPlayer.
Currently I’m confused because when I initialize the object within onAppear, then everything works fine.
When I use init() for initialization, then the object is nil afterwards.
I used the debugger: It’s perfectly clear, that the code within init, has been executed before the object becomes used. Nevertheless it’s nil, respectively “
What goes wrong here?
Can someone explain the described findings?
import AVFAudio
struct ContentView: View {
@State var player: AVAudioPlayer? = nil
@State var isPlaying = false
let url = Bundle.main.url(forResource: "demo01", withExtension: "m4a")
// Results in
init() {
// if let url {
// do {
// player = try AVAudioPlayer(contentsOf: url)
// } catch {
// print(error.localizedDescription)
// }
// }
}
var body: some View {
VStack(spacing: 25) {
Button {
if let player {
if (isPlaying == true) {
player.pause()
isPlaying = false
} else {
player.prepareToPlay()
player.play()
isPlaying = true
}
}
} label: {
Label(isPlaying ? "Pause" : "Play",
systemImage: isPlaying ? "stop.circle" : "play.circle")
}
}
.onAppear() {
if let url {
do {
player = try AVAudioPlayer(contentsOf: url) //
} catch {
print(error.localizedDescription)
}
}
}
.padding()
}
}