[swift] 재생 중인 사운드 일시정지하기

iOS 애플리케이션에서 사운드를 재생할 때, 사운드를 일시정지하는 기능은 유용합니다. 이번 글에서는 Swift를 사용하여 현재 재생 중인 사운드를 일시정지하는 방법에 대해 알아보겠습니다.

AVAudioPlayer 사용하기

AVAudioPlayer는 iOS에서 사운드를 재생하기 위해 사용되는 클래스입니다. 이 클래스를 사용하여 사운드를 재생하고 일시정지할 수 있습니다.

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?.play()
        } catch {
            print("Error playing sound: \(error.localizedDescription)")
        }
    }
    
    func pauseSound() {
        audioPlayer?.pause()
    }
}

위의 예제 코드에서는 SoundPlayer라는 클래스를 정의하고, playSound() 메서드를 사용하여 사운드를 재생합니다. 사운드 파일은 번들에서 가져오는데, 예제에서는 “sound.mp3”라는 파일을 사용하도록 되어 있습니다. pauseSound() 메서드를 호출하면 현재 재생 중인 사운드를 일시정지할 수 있습니다.

사용 예시

let soundPlayer = SoundPlayer()
soundPlayer.playSound()
// 사운드 재생 중
soundPlayer.pauseSound()
// 사운드 일시정지

위의 예시 코드에서는 SoundPlayer 인스턴스를 생성하고, playSound() 메서드를 호출하여 사운드를 재생합니다. 사운드가 재생 중일 때 pauseSound() 메서드를 호출하여 사운드를 일시정지할 수 있습니다.

마무리

이제 위의 코드를 참고하여 Swift를 사용하여 재생 중인 사운드를 일시정지하는 기능을 구현할 수 있습니다. AVAudioPlayer 클래스를 사용하여 사운드를 제어하는 방법을 익혀두면, 더욱 다양한 사운드 제어 기능을 구현할 수 있습니다.

참고 자료