[swift] 음악 파일의 재생 시간 가져오기

iOS 앱 개발 중에 음악 관련 기능을 구현해야 한다면, 음악 파일의 재생 시간을 가져와야 할 때가 있습니다. Swift를 사용하여 음악 파일의 재생 시간을 가져오는 방법에 대해 알아보겠습니다.

AVPlayer를 이용한 재생 시간 가져오기

AVPlayer는 iOS에서 음악 파일을 재생할 때 많이 사용되는 클래스입니다. AVPlayer를 이용하여 음악 파일의 재생 시간을 가져오는 방법은 다음과 같습니다.

import AVFoundation

// AVPlayer를 사용하여 재생 시간 가져오기
func getDurationOfAudioFile(url: URL) -> CMTime {
    let asset = AVURLAsset(url: url)
    let playerItem = AVPlayerItem(asset: asset)
    let player = AVPlayer(playerItem: playerItem)
    
    // 재생 시간 가져오기
    let duration = playerItem.duration
    
    return duration
}

// 예시 사용
let audioURL = URL(fileURLWithPath: "path/to/audio/file.mp3")
let duration = getDurationOfAudioFile(url: audioURL)
print("재생 시간: \(CMTimeGetSeconds(duration)) 초")

위의 코드에서는 AVPlayer를 생성한 후, AVURLAsset와 AVPlayerItem을 생성하여 음악 파일의 속성과 재생 시간을 가져옵니다. 가져온 재생 시간은 CMTime 형식으로 반환되며, CMTimeGetSeconds 함수를 이용하여 초 단위로 변환할 수 있습니다.

AVAudioPlayer를 이용한 재생 시간 가져오기

AVAudioPlayer는 AVFoundation 프레임워크에 포함된 클래스로, 단일 음악 파일을 재생할 때 사용됩니다. AVAudioPlayer를 이용하여 음악 파일의 재생 시간을 가져오는 방법은 다음과 같습니다.

import AVFoundation

// AVAudioPlayer를 사용하여 재생 시간 가져오기
func getDurationOfAudioFile(url: URL) -> TimeInterval {
    guard let audioPlayer = try? AVAudioPlayer(contentsOf: url) else {
        return 0
    }
    
    // 재생 시간 가져오기
    let duration = audioPlayer.duration
    
    return duration
}

// 예시 사용
let audioURL = URL(fileURLWithPath: "path/to/audio/file.mp3")
let duration = getDurationOfAudioFile(url: audioURL)
print("재생 시간: \(duration) 초")

위의 코드에서는 AVAudioPlayer를 생성한 후, 해당 재생자의 duration 속성을 사용하여 음악 파일의 재생 시간을 가져옵니다.

결론

이상으로 Swift를 사용하여 음악 파일의 재생 시간을 가져오는 방법에 대해 알아보았습니다. AVPlayer와 AVAudioPlayer를 이용하여 간단하게 음악 파일의 재생 시간을 가져올 수 있습니다. 프로젝트에 맞는 방법을 선택하여 음악 관련 기능을 구현해보세요.

참고: