如何使UISlider匹配音频进度 [英] How To Make UISlider match Audio progress

查看:111
本文介绍了如何使UISlider匹配音频进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的音乐应用程序,我想知道如何制作UiSlider来跟踪音频文件的进度.到目前为止,这是我的项目:

I am creating a simple music app, and I was wondering how I can make a UiSlider to follow the progress of a audio file. Here's my project so far:

代码:

import UIKit
import AVFoundation

class SongDetailViewController: UITableViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "Song Name", ofType: "mp3")!))
            audioPlayer.prepareToPlay()

            var audioSession = AVAudioSession.sharedInstance()

            do {
                try audioSession.setCategory(AVAudioSessionCategoryPlayback)
            }
        }

        catch {
            print(error)
        }
    }
//    Buttons

//    Dismiss
    @IBAction func dismiss(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

//    Play
    @IBAction func play(_ sender: Any) {
        audioPlayer.stop()
        audioPlayer.play()
    }

//    Pause
    @IBAction func pause(_ sender: Any) {
        audioPlayer.pause()
    }

//    Restart
    @IBAction func restart(_ sender: Any) {
        audioPlayer.currentTime = 0
    }

}

我想创建类似于Apple Music应用程序的uislider,该应用程序会跟踪音频文件的进度,并且每当用户滑动球形物体时(大声笑),它都会转到歌曲的那个时间.如果您可以给我一些代码来完成此操作,那就太好了!

I'm wanting to create the uislider similar to the Apple Music app where it follows the audio file's progress and whenever the user slides the ball thing (lol) it goes to that time of the song. If you could give me some code to complete this, that would be amazing!

请记住,我对编码还很陌生,但仍在学习敏捷,因此请保持简单:-)再次感谢!

Please keep in mind that I am fairly new to coding and am still learning swift, so keep it simple :-) Thanks again!

推荐答案

如果切换为使用AVPlayer,则可以在AVPlayer中添加periodicTimeObserver.在下面的示例中,您将每1/30秒收到一次回调…

If you switch to using an AVPlayer, you can add a periodicTimeObserver to your AVPlayer. In the example below you'll get a callback every 1/30 second…

let player = AVPlayer(url: Bundle.main.url(forResource: "Song Name", withExtension: "mp3")!)

player.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 30), queue: .main) { time in

    let fraction = CMTimeGetSeconds(time) / CMTimeGetSeconds(player.currentItem!.duration)

    self.slider.value = fraction
}

在代码中创建audioPlayer的位置,请替换为上面的代码.

Where you create an audioPlayer in your code, replace with the code above.

这篇关于如何使UISlider匹配音频进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆