简体   繁体   中英

AVPlayer progress with UISlider Swift

I'm trying to use a slider to control Audio and everything works fine, but when I try to make the slider value equal to the player current time it crashes.
However, if I print something inside the updateSlider function, it appears and works fine.

override func viewDidLoad() 
{    
    songTitle.text = mainSongTitle
    background.image = image
    mainImageView.image = image    
    downloadFileFromURL(url: URL(string: previewURL)!)             
    var time = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateSlider), userInfo: nil, repeats: true)  
}    

func downloadFileFromURL(url : URL)
{
    var downloadTask = URLSessionDownloadTask()
    downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: 
    {   
        customURL , response , error in
        self.play(url: customURL!)
        self.slider.maximumValue = Float(player.duration)
    })
    downloadTask.resume()
}

func play(url : URL)
{
    do
    {
        player = try AVAudioPlayer(contentsOf: url)
        player.prepareToPlay()
        player.play()      
    }
    catch 
    {
        print(error)
    }
}

@IBAction func PlayPressed(_ sender: Any) 
{            
    if player.isPlaying
    {
        player.pause()                
    }
    else
    {
        player.play()
    }
}

@IBAction func ChangerTimePlayer(_ sender: Any) 
{
    player.stop()
    player.currentTime = TimeInterval(slider.value)
    player.prepareToPlay()
    player.play()
}

func updateSlider()
{
    slider.value = Float(player.currentTime)
}

Maybe you should do something like:

func updateSlider(){
    slider.value = Float(player.currentTime/player.duration)
}

Your download completion task needs to be called on the main thread to safely use UIKit (your slider):

DispatchQueue.main.async {
    self.play(url: customURL!)
    self.slider.maximumValue = Float(player.duration)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM