如何解决将 AVAudioPlayer 与 swiftUI 一起使用时在滑块上移动拇指的问题
使用 swiftUI(最新版本为 2 月 24 日)
我正在播放音频文件 (soundFile.mp3),一切正常。 (移至结尾、开头、+/- 15 秒、暂停、播放)
但是,我无法通过滑块上的“拇指”手动移动滑块。 但是当我暂停音频时,拇指会随着音频播放和停止而移动
有人对我如何解决这个问题有任何想法吗????
将不胜感激
菲尔
swiftUI 文件(删减一点)如下:
...
import SwiftUI
import AVFoundation
var audioPlayer: AVAudioPlayer?
struct ContentView: View {
@State private var sound: String = "soundFile"
@State private var type: String = "mp3"
@State private var myTime:CGFloat = 0
@State private var timeDuration:CGFloat = 10
@State private var myDuration:CGFloat = 10
@State var currentValue = 4.0
@State var myCurrentTime = 4.0
@State var isPlaying: Bool = true
var body: some View
{
VStack
{
Text("Playing")
.frame(width: 00,height: 60,alignment: .center)
.scaledToFit()
.onAppear(perform: {
playSound(sound: sound,type: type)
})
}
.background(Color.green)
HStack
{
Spacer()
Image(systemName: self.isPlaying ? "pause.circle.fill" : "play.circle.fill")
.resizable()
.frame(width: 30,height: 30)
.aspectRatio(contentMode: .fit)
.onTapGesture {
if(audioPlayer?.currentTime != Double(audioPlayer!.duration - 0.1))
{
if(isPlaying == true)
{
pauseMySound()
isPlaying = false
}
else
{
playMySound()
isPlaying = true
}
}
}
Spacer()
}
VStack {
Slider( value: $myCurrentTime,in: 0.0...Double(myDuration),step: 1,minimumValueLabel: Text("0"),maximumValueLabel: Text("\(Int(myDuration))") )
{
}
Text("\(Int(myCurrentTime)) Sec's")
}
.padding(.horizontal,15)
}
func playSound(sound: String,type: String)
{
DispatchQueue.global(qos: .background).async {
while true
{
let currentTime = audioPlayer?.currentTime
myCurrentTime = currentTime ?? 0
}
}
let path = Bundle.main.path(forResource: sound,ofType: type)
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path! ))
audioPlayer?.play()
DispatchQueue.global(qos: .background).async {
while true
{
let currentTime = audioPlayer!.currentTime / audioPlayer!.duration
myDuration = CGFloat(audioPlayer!.duration)
}
}
} catch {
print("error")
}
}
}
func playMySound()
{
audioPlayer!.play()
}
func pauseMySound()
{
audioPlayer!.pause()
}
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。