我尝试构建一个播放mp3文件的应用程序,我希望获得当前时间和持续时间,以便在播放时将其显示在2个标签中。
我使用了这段代码,在持续时间内显示了歌曲的一半时间,
例如:如果歌曲的持续时间是20分40秒,那就显示了一半就像10:20
但是在当前时间没有取得进展,它显示00:00
谢谢。
let duration = Int((player1?.duration)!)
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
durLabel.text = NSString(format: "%02d:%02d", minutes2,seconds2) as String
let currentTime1 = Int((player1?.currentTime)!)
let minutes = currentTime1/60
let seconds = currentTime1 - minutes * 60
curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String
答案 0 :(得分:3)
// this is to compute and show remaining time
let duration = Int((player1?.duration - (player1?.currentTime))!)
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
durLabel.text = NSString(format: "%02d:%02d", minutes2,seconds2) as String
//This is to show and compute current time
let currentTime1 = Int((player1?.currentTime)!)
let minutes = currentTime1/60
let seconds = currentTime1 - minutes * 60
curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String
答案 1 :(得分:1)
玩家当前时间不会自动更新。相反,您必须使用计时器定期更新当前时间。如果您想了解更多详细信息,请查看以下主题。
答案 2 :(得分:0)
如果您有Slider来搜索mp3文件,就像这样:
@IBOutlet weak var slidetOutlet: UISlider!
您可以这样更新UILabel:
self.lblPlayerTime.text = self.secondsToHoursMinutesSeconds(seconds: Double( self.slidetOutlet.value ))
初始化播放器和滑块:
func playerInit() {
guard let url = URL(string: urlAudio) else {
return
}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player!.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: DispatchQueue.main) { (CMTime) -> Void in
if self.player!.currentItem?.status == .readyToPlay {
let time : Float64 = CMTimeGetSeconds(self.player!.currentTime());
self.slidetOutlet.value = Float ( time )
self.slidetOutlet.minimumValue = 0
let duration : CMTime = self.playerItem!.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
self.slidetOutlet.maximumValue = Float(seconds)
self.lblStartTimePlayer.text = self.secondsToHoursMinutesSeconds(seconds: seconds)
self.lblPlayerTime.text = self.secondsToHoursMinutesSeconds(seconds: Double( self.slidetOutlet.value ))
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
并转换时间:
func secondsToHoursMinutesSeconds (seconds : Double) -> (String) {
let (hr, minf) = modf (seconds / 3600)
let (min, secf) = modf (60 * minf)
return ("\(Int(hr)):\(Int(min)):\(Int(60 * secf))")
}