AVPlayer与UISlider Swift一起进步

时间:2016-11-19 16:06:36

标签: ios swift avplayer uislider

我尝试使用滑块控制音频,一切正常,但当我尝试使滑块值等于播放器当前时间时,它会崩溃。
但是,如果我在updateSlider函数内打印一些内容,它会显示并正常工作。

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)
}

2 个答案:

答案 0 :(得分:0)

也许你应该这样做:

connection.on('disconnected', () => {
    logger.debug(`Mongoose connection disconnected`);
    mongoose.connect(path);
  });

答案 1 :(得分:0)

您需要在主线程上调用您的下载完成任务,以安全地使用UIKit(您的滑块):

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