[swift] 특정 시점에서의 사운드 반복 재생하기

iOS 애플리케이션을 개발하다 보면, 특정 시점에서 사운드를 반복해서 재생해야 할 때가 있습니다. 예를 들어 게임에서 배경 음악을 무한 반복하거나, 알림 소리를 일정 간격으로 반복해서 재생하는 경우입니다. 이러한 기능을 구현하는 방법을 알아보겠습니다.

AVAudioPlayer를 사용한 사운드 반복 재생

AVAudioPlayer 클래스를 사용하면 사운드 파일을 재생할 수 있습니다. 다음은 AVAudioPlayer를 사용하여 사운드 파일을 반복해서 재생하는 예제 코드입니다.

import AVFoundation

class SoundPlayer {
    var audioPlayer: AVAudioPlayer?

    func playSound() {
        guard let soundUrl = Bundle.main.url(forResource: "sound", withExtension: "mp3") else { return }
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundUrl)
            audioPlayer?.numberOfLoops = -1 // 사운드를 무한 반복
            audioPlayer?.prepareToPlay()
            audioPlayer?.play()
        } catch {
            print("사운드 재생 중 오류 발생: \(error.localizedDescription)")
        }
    }
    
    func stopSound() {
        audioPlayer?.stop()
    }
}

위의 예제 코드에서 playSound() 메서드를 호출하면 “sound.mp3” 파일이 무한 반복으로 재생됩니다. stopSound() 메서드를 호출하면 사운드 재생이 멈춥니다.

AVPlayer를 사용한 사운드 반복 재생

AVPlayer를 사용하면 더욱 복잡한 사운드 재생 기능을 구현할 수 있습니다. 아래는 AVPlayer를 사용하여 사운드 파일을 특정 시점에서 반복해서 재생하는 예제 코드입니다.

import AVFoundation

class SoundPlayer {
    var player: AVPlayer?
    
    func playSound() {
        guard let url = Bundle.main.url(forResource: "sound", withExtension: "mp3") else { return }
        
        player = AVPlayer(url: url)
        
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
        
        player?.play()
    }
    
    @objc func playerDidFinishPlaying(_ notification: Notification) {
        player?.seek(to: CMTime.zero)
        player?.play()
    }
    
    func stopSound() {
        player?.pause()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

위의 예제 코드에서 playSound() 메서드를 호출하면 “sound.mp3” 파일이 재생됩니다. 사운드가 종료되면 playerDidFinishPlaying(_:) 메서드를 통해 사운드를 특정 시점으로 이동시킨 후 다시 재생합니다. stopSound() 메서드를 호출하면 사운드 재생이 일시 정지됩니다.

마무리

이제 AVAudioPlayer와 AVPlayer를 사용하여 특정 시점에서 사운드를 반복해서 재생하는 방법에 대해 알아보았습니다. 원하는 기능에 따라 적절한 방법을 선택하여 사운드 반복 재생을 구현해보세요.


참고 문서: