我正在使用SwiftUI构建播放器。它正在工作,我播放和暂停音频,更改幻灯片值,音频更改音频位置。
我在音频结尾处遇到问题,该按钮未使用播放图标更新其标签,但仍保留在暂停图标中。
我认为该值不会改变,因为在Button结构中,标签没有收到Binding值,因此它不会更新其值。我的猜测是带有@ Binding var的button的子类,如果更改其值,则标签也会更改。
您认为这是问题吗?
在播放中:
最后我想这样:
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
}
}
这里是这里
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
}
}