I'm building a player with SwiftUI. It's working, I play and pause the audio, changing the slide value, the audio is changing the audio position.
I've a problem at the end of the audio, the button doesn't update its label with play icon, but it's remaining in the pause icon.
during the play:
at the end I would like this:
struct BubbleAudio: View {
let text: String
var unzipPath: URL
@State private var playValue: TimeInterval = 0.0
@State private var isPlaying: Bool = false
@State private var playerDuration: TimeInterval = 120
@State private var timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text(playValue.stringFromTimeInterval())
.font(.system(size: 11, weight: .light))
.offset(y: +10)
.onReceive(timer) { _ in
if self.isPlaying {
if let currentTime = Sounds.audioPlayer?.currentTime {
self.playValue = currentTime
}
}
else {
self.isPlaying = false
self.timer.upstream.connect().cancel()
}
}
HStack {
Button(action: {
if self.isPlaying {
self.isPlaying.toggle()
Sounds.audioPlayer?.pause()
}
else {
self.timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
if Sounds.playWAAudio(text: self.text, unzipPath: self.unzipPath) {
self.isPlaying.toggle()
}
}
}, label: {
if isPlaying {
Image(systemName: "pause")
.font(Font.system(.title).bold())
}
else {
Image(systemName: "play.fill")
.font(Font.system(.title).bold())
}
})
.frame(width: 35)
.fixedSize()
Slider(value: $playValue, in: TimeInterval(0.0)...playerDuration, onEditingChanged: { _ in
self.changeSliderValue()
})
.frame(width: 200, height: 10, alignment: Alignment.center)
Text(playerDuration.stringFromTimeInterval())
.font(.system(size: 11, weight: .light))
}
}
.onAppear() {
self.playerDuration = Sounds.getDuration(text: self.text, unzipPath: self.unzipPath)
print(self.playerDuration)
}
}
func changeSliderValue() {
Sounds.audioPlayer?.currentTime = playValue
}
}
It is rather here, in .onReceive(timer) {
if let currentTime = Sounds.audioPlayer?.currentTime {
self.playValue = currentTime
// reset playValue, so reset isPlaying if needed
if currentTime == TimeInterval(0.0) { // only explicitly
self.isPlaying = false
}
}