このAVAudioPlayerは、簡単にPlayersのインターバルが取得できる特徴がある。
class ViewController: UIViewController {
var player = AVAudioPlayer()
var url = NSUNL()
var slider = UISlider()
var Tim = Timer()
override func viewDidLoad(){
url = URL(string: “https://url/audio_file.m4a”)! as NSURL
player = try! AVAudioPlayer(contentsOf: url as URL)
PlayMusic()
slider.frame = CGRect(x: 10, y: self.view.frame.size.height-44, width: self.view.frame.size.width-20, 44)
self.view.addSubview(slider)
let btn1 = UIButton()
btn1.frame = CGRect(x: 0, y: 300, width: 320, height: 40)
btn1.addTarget(self, action: #selector(playing(playing:)), for: .touchUpInside)
self.view.addSubview(btn1)
}
func PlayMusic(){
let t = player.duration
let t2 = player.currentTime
slider.maximumValue = Float(t)
slider.minimumValue = 0.0
slider.value = Float(t2)
Tim = Timer.scheduledTimer(interval: 0.1, target: self, selector: #selector(tim(tim:)), userInfo: nil, repeats: true)
}
@objc func playing(playing: UIButton){
plsyer.play()
PlayMusic()
}
@objc tim(tim: Timer){
let t = player.duration
let t2 = player.currentTime
slider.maximumValue = Float(t)
slider.minimumValue = 0.0
slider.value = Float(t2)
}
}
URLは独自のものを使ってください。
AVAudioPlayerはiOSのデバイス内の音声出力は確認できていますが、外部URLはどうか?
ボタンタップからの再生で、スライダーだけの UIの実装です。