재수노강 2021. 10. 17. 21:00
728x90

아이폰에서 노래를 재생하거나 소리를 녹음하는 것과 같이 소리와 관련된 동작이 많이 있습니다.

 

오디오 사용을 위한 준비

AVFoundation을 추가하고, AVAudioPlayerDelegate를 상속받습니다.

그리고 오디오 파일로 AVAudioPlayer를 생성합니다.

import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {
	
    var audioPlayer: AVAudioPlayer!
    var audioFile: URL!
    
	override func viewDidLoad() {
    	super.viewDidLoad()
    	audioFile = Bundle.main.url(forResource: "Sicilian_Breeze", withExtension: "mp3")
        initPlay()
    }
    
    func initPlay() {
    	do {
        	audioPlayer = try AVAudioPlayer(contentsOf: audioFile)
        } catch let error as NSError {
        	print("Error-initPlay : \(errer)")
        }
        audioPlayer.delegate = self
        audioPlayer.prepareToPlay()
        audioPlayer.volume = 1.0	// 0.0 ~ 1.0
    }
}

 

오디오 플레이어 조작

play, pause, stop으로 오디오 플레이어의 동작을 제어할 수 있습니다.

audioPlayer.play()
audioPlayer.pause()
audioPlayer.stop()

 

녹음을 위한 준비

녹음을 위해서는 AVAudioRecorderDelegate를 상속하고 AVAudioRecoder 인스턴스를 이용합니다.

class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {
	var audioRecorder: AVAudioRecorder!
}

 

녹음한 파일을 위치를 지정해야 합니다.

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
audioFile = documentDirectory.appendingPathComponent("recordFile.m4a")

 

녹음하기

녹음하기 위한 설정값과 함께 AvAudioRecorder 인스턴스를 생성합니다.

    func initRecord() {
        let recordSettings = [
            AVFormatIDKey: NSNumber(value: kAudioFormatAppleLossless as UInt32),
            AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
            AVEncoderBitRateKey: 320000,
            AVNumberOfChannelsKey: 2,
            AVSampleRateKey: 44100.0] as [String: Any]
        do {
            audioRecorder = try AVAudioRecorder(url: audioFile, settings: recordSettings)
        } catch let error as NSError {
            print("Error-initRecord : \(error)")
        }
        audioRecorder.delegate = self

        let session = AVAudioSession.sharedInstance()
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch let error as NSError {
            print(" Error-setCategory : \(error)")
        }
        do {
            try session.setActive(true)
        } catch let error as NSError {
            print(" Error-setActive : \(error)")
        }
    }

음악 재생은 앱이 백그라운드로 내려가더라도 재생될 경우가 있는데, 이와 같은 시스템과의 커뮤니케이션은 AVAudioSession을 통해서 처리할 수 있습니다.

 

Reference

https://developer.apple.com/documentation/avfoundation

https://developer.apple.com/documentation/avfaudio/avaudiosession