Swift 4 - 带 AVAudioPlayer 的 UISlider
Swift 4 - UISlider with AVAudioPlayer
我正在使用 AVAudioPlayer 播放音频,现在我正在尝试使用 UISlider 作为音频时间轴
@IBOutlet var audioSlider: UISlider!
override func viewDidLoad() {
audioSlider.setValue(0, animated: false)
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: (#selector(PlayerController.updateTimer)), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
if(audio != nil)
{
audioSlider.setValue(Float(Int((self.audio?.currentTime)!)), animated: false)
}
}
但我认为它不起作用,我的 UISlider 会立即从头到尾。我希望我的 UISlider
能顺利过渡
这是我播放音频的方式:
@IBAction func playButtonPressed(_ sender: Any) {
if(playButton.titleLabel?.text == "Play")
{
postPlay(postid: self.postid) { results in
DispatchQueue.main.async {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
}
catch {
}
self.audio?.delegate = self
self.audio?.numberOfLoops = 0
self.playButton.titleLabel?.text = "Stop"
self.audio?.play()
self.playCount = self.playCount + 1
self.plays.text = "Total Plays: " + self.playCount.description
}
}
}
else
{
playButton.titleLabel?.text = "Resume"
audio?.stop()
}
}
UISlider 需要介于 0.0 和 1.0 之间的值。为此,您必须将当前进度除以总时间。
例如
audioSlider.setValue(Float(self.audio?.currentTime! / self.audio?.duration!), animated: false)
我正在使用 AVAudioPlayer 播放音频,现在我正在尝试使用 UISlider 作为音频时间轴
@IBOutlet var audioSlider: UISlider!
override func viewDidLoad() {
audioSlider.setValue(0, animated: false)
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: (#selector(PlayerController.updateTimer)), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
if(audio != nil)
{
audioSlider.setValue(Float(Int((self.audio?.currentTime)!)), animated: false)
}
}
但我认为它不起作用,我的 UISlider 会立即从头到尾。我希望我的 UISlider
能顺利过渡这是我播放音频的方式:
@IBAction func playButtonPressed(_ sender: Any) {
if(playButton.titleLabel?.text == "Play")
{
postPlay(postid: self.postid) { results in
DispatchQueue.main.async {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
}
catch {
}
self.audio?.delegate = self
self.audio?.numberOfLoops = 0
self.playButton.titleLabel?.text = "Stop"
self.audio?.play()
self.playCount = self.playCount + 1
self.plays.text = "Total Plays: " + self.playCount.description
}
}
}
else
{
playButton.titleLabel?.text = "Resume"
audio?.stop()
}
}
UISlider 需要介于 0.0 和 1.0 之间的值。为此,您必须将当前进度除以总时间。
例如
audioSlider.setValue(Float(self.audio?.currentTime! / self.audio?.duration!), animated: false)