본문 바로가기
iOS, Swift 개발

AvPlayer 재생 시간과 소수점 변환 구하기

by Nin J 2024. 3. 15.

안녕하세요.

var Player : AVPlayer?

1. Duration 전체 재생 시간 구하기. 

단 예외적으로 플레이 파일 로딩시 Fail이 발생 될수 있어 duration 시간이 없을수도 있으므로

.isNaN 이라는 Exception 처리를 하여 안정성 높이는 코드가 필요.

if let duration = self.Player?.currentItem?.asset.duration{

   let seconds = CMTimeGetSeconds(duration)           

   if !seconds.isNaN {

       sendDic.setValue(String(seconds), forKey: "param3")

      debugPrint("Duration  Seconds : ",String(seconds))

   }

}

2. currentTime() 현재 재생 시간 구하기. 

단 예외적으로 플레이 파일 로딩시 Fail이 발생 될수 있어 duration 시간이 없을수도 있으므로

.isNaN 이라는 Exception 처리를 하여 안정성 높이는 코드가 필요.

if let duration = self.Player?.currentItem?.currentTime(){

   let seconds = CMTimeGetSeconds(duration)           

   if !seconds.isNaN {

       sendDic.setValue(String(seconds), forKey: "param3")

      debugPrint("CurrentTime  Seconds : ",String(seconds))

   }

}

 

추가 적으로 

1. 반올림(round) : 소수점이 5보다 크거나 같으면 올리고 5보다 작으면 내리고

ex: 5.3 -> 5.0, 5.6 -> 6.0

if let duration = self.Player?.currentItem?.currentTime(){

   let seconds = CMTimeGetSeconds(duration){

       debugPrint("round value : ",round(seconds))

   }

}

2. 올림(ceil) : 소수점이 0보다 크면 무조건 올리고

ex: 5.3 -> 6.0, 5.6 -> 6.0

if let duration = self.Player?.currentItem?.currentTime(){

   let seconds = CMTimeGetSeconds(duration){

       debugPrint("round value : ",ceil(seconds))

   }

}

3. 내림(floor) : 소수점 무조건 내리고

ex: 5.3 -> 5.0, 5.6 -> 5.0

if let duration = self.Player?.currentItem?.currentTime(){

   let seconds = CMTimeGetSeconds(duration){

       debugPrint("round value : ",floor(seconds))

   }

}

4. 버림(trunc) : 소수점 그냥 버리고 

ex: 5.3 -> 5.0, 5.6 -> 5.0

if let duration = self.Player?.currentItem?.currentTime(){

   let seconds = CMTimeGetSeconds(duration){

       debugPrint("round value : ",trunc(seconds))

   }

}