[swift] 사운드 재생 시간 동안 프로그레스 애니메이션 효과 주기

사운드를 재생할 때 프로그레스 애니메이션을 추가하여 사용자에게 시각적인 피드백을 제공하는 것은 앱 또는 웹사이트에서 공통적으로 사용되는 기능입니다. 이번 글에서는 Swift 언어를 사용하여 사운드 재생 시간 동안 프로그레스 애니메이션 효과를 주는 방법에 대해 알아보겠습니다.

1. AVAudioPlayer 사용

AVAudioPlayer 라이브러리를 사용하여 사운드를 재생할 수 있습니다. 사운드 파일을 재생하기 전에 먼저 AVAudioPlayer 객체를 초기화해야합니다.

다음은 사운드 파일을 재생하는 코드입니다.

guard let soundUrl = Bundle.main.url(forResource: "sound", withExtension: "mp3") else { return }
do {
    let audioPlayer = try AVAudioPlayer(contentsOf: soundUrl)
    audioPlayer.play()
} catch {
    print("Failed to play sound: \(error)")
}

2. 애니메이션 추가

사운드를 재생하는 동안 프로그레스 애니메이션을 주기 위해 CADisplayLink를 사용할 수 있습니다.

var progress = 0.0
let duration = audioPlayer.duration
    
let displayLink = CADisplayLink(target: self, selector: #selector(updateProgress))
displayLink.add(to: .current, forMode: .default)
        
@objc func updateProgress() {
    if progress >= duration {
        displayLink.invalidate()
    } else {
        progress += displayLink.duration
        let percent = progress / duration
        updateProgressBar(percent)
    }
}

func updateProgressBar(_ percent: Double) {
    // 프로그레스 바 업데이트 로직 구현
}

위의 코드에서 updateProgressBar 함수는 프로그레스 바를 업데이트하는 로직을 담당합니다. 실제로 프로그레스 바를 구현하는 방법은 UI 요구사항과 디자인에 따라 다를 수 있습니다.

3. 애니메이션 효과 적용하기

프로그레스 바를 업데이트하는 로직을 추가한 후에는 updateProgressBar 함수에서 실제로 애니메이션 효과를 적용할 수 있습니다. 예를 들어, 프로그레스 바의 너비를 조절하는 애니메이션을 추가할 수 있습니다.

func updateProgressBar(_ percent: Double) {
    UIView.animate(withDuration: 0.3) {
        self.progressBarWidthConstraint.constant = self.progressBarContainerView.frame.width * CGFloat(percent)
        self.view.layoutIfNeeded()
    }
}

위의 코드에서 progressBarWidthConstraint는 프로그레스 바의 너비를 제어하는 NSLayoutConstraint 객체입니다. updateProgressBar 함수 내에서 해당 제약 조건의 constant 값을 업데이트하면 프로그레스 바의 너비가 변화하게 됩니다.

이제 사운드를 재생할 때 프로그레스 애니메이션 효과를 주는 방법에 대해 알아보았습니다. 원하는 결과를 얻기 위해 예시 코드를 참고하시고, 앱 또는 웹사이트의 요구사항에 맞게 수정하여 사용해보세요.

참고 자료