gpt4 book ai didi

ios - swift 3 : How to add UISlider?

转载 作者:搜寻专家 更新时间:2023-11-01 07:14:49 25 4
gpt4 key购买 nike

我有 ViewControllerAVAudioPlayer。现在我有了这段代码

import UIKit
import AVFoundation

var audioPlayer = AVAudioPlayer()

class ViewController: UIViewController {

@IBOutlet weak var slider: UISlider!
@IBOutlet weak var playButton: UIButton!
var index = 0
var timer: Timer?

override func viewDidLoad() {
super.viewDidLoad()

if index == 0{

let url = Bundle.main.url(forResource: "1", withExtension: "mp3")!

do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.prepareToPlay()
//audioPlayer.play()
//play(sender:AnyObject.self as AnyObject)

} catch let error {
print(error.localizedDescription)
}
}
}

@IBAction func slide(_ slider: UISlider) {
audioPlayer.currentTime = TimeInterval(slider.value)
}

@IBAction func play(sender: AnyObject) {
if !audioPlayer.isPlaying{
audioPlayer.play()
// **** The line below is the new line ****
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.updateSlider), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
} else {
audioPlayer.pause()
playButton.setImage(UIImage(named: "pause.png"), for: UIControlState.normal)
timer?.invalidate()
}
}

func updateSlider(_ timer: Timer) {
slider.value = Float(audioPlayer.currentTime)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

我想添加 UISlider 来改变音频文件的滑动。怎么做?

最佳答案

首先,您必须从 slider 添加一个新的 IBAction 以确保您的类在 slider 值更改时得到通知(在此处查找“响应用户交互”:https://developer.apple.com/reference/uikit/uislider#2557863)

在此事件处理程序中,您必须设置音频当前时间

@IBAction func slide(_ slider: UISlider) {
audioPlayer.currentTime = TimeInterval(slider.value)
}

为确保 slider 根据当前时间更新其值,您必须在启动播放器时添加一个计时器,该计时器调用自定义方法来更新 slider 值。

@IBAction func play(sender: AnyObject) {
if !audioPlayer.isPlaying{
audioPlayer.play()
// **** The line below is the new line ****
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.updateSlider), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .commonModes)
} else {
audioPlayer.pause()
playButton.setImage(UIImage(named: "pause.png"), for: UIControlState.normal)
timer.invalidate()
}
}

然后你必须创建更新 slider 值的方法

func updateSlider(_ timer: Timer) {
slider.value = Float(audioPlayer.currentTime)
}

然后你必须设置 slider 的最大值

override func viewDidLoad() {
super.viewDidLoad()

if index == 0{

let url = Bundle.main.url(forResource: "1", withExtension: "mp3")!

do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.prepareToPlay()
// **** These two lines below are new ****
slider.maximumValue = Float(audioPlayer.duration)
slider.value = 0.0
} catch let error {
print(error.localizedDescription)
}
}
}

最后你必须在你的 IBOutlets 下面创建一个属性来保存计时器

var timer: Timer?

关于ios - swift 3 : How to add UISlider?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com