본문 바로가기
Swift

오디오 녹음 및 재생 AVAudioRecorder & AVAudioPlayer

by 루에 2015. 10. 29.
반응형

오디오 녹음기

init(URL url: NSURL, settings: [String : AnyObject]) throws

로 초기화한다.

플레이어는 url만 설정하면 된다.


녹음 환경 설정은 딕셔너리 형태로 한다. 옵션은 아래와 같다.

AVFormatIDKey : 녹음 포맷, 코어 오디오에 정의된 포맷 문자 사용

AVSampleRateKey : 샘플링 레이트

AVLinearPCMBitDepthKey : 녹음에 사용할 비트

AVEncoderAudioQualityKey : 녹음 품질


녹음 기능에 관련된 메소드

func prepareToRecord() -> Bool    // 녹음 준비과정. 파일 생성함.

func record() -> Bool    // 파일에 녹음 수행하거나 중지

func recordForDuration(duration: NSTimeInterval) -> Bool    // duration만큼 녹음하고 자동으로 멈춘다.

func pause()    // 녹음 정지

func stop()    // 녹음 중지하고 파일을 닫는다.

func deleteRecording() -> Bool    // 파일 삭제


기본적인 기능을 구현한 코드는 아래와 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
 
import UIKit
import AVFoundation
 
class ViewController: UIViewController, AVAudioRecorderDelegate{
 
    var recorder : AVAudioRecorder!
    var player : AVAudioPlayer!
    let setting = [
        AVSampleRateKey : 44100,
        AVLinearPCMBitDepthKey:16
    ]
    let docPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
 NSSearchPathDomainMask.UserDomainMask, true)[0as NSString
    var aUrl : NSURL!
    
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
        //
    }
 
    @IBAction func recordStart(sender: AnyObject) {
        recorder = getAudio()
        if recorder.prepareToRecord() {
            print("record start")
            recorder.recordForDuration(10)
        }
    }
 
    @IBAction func recordStop(sender: AnyObject) {
        if nil != recorder && recorder.recording {
            print("record stop")
            recorder.stop()
        }
    }
    
    @IBAction func play(sender: AnyObject) {
        player = try! AVAudioPlayer(contentsOfURL: aUrl)
        print("audio play")
        player.play()
    }
    
    @IBAction func pause(sender: AnyObject) {
        if nil != player && player.playing {
            print("audio stop")
            player.stop()
        }
    }
    
    func getAudio() -> AVAudioRecorder{
        let formatter = NSDateFormatter()
        formatter.dateFormat = "YYYY.MM.dd.hh.mm.DD"
        let fileName = String(format: "%@.caf", formatter.stringFromDate(NSDate()))
        print("fileName : \(fileName)")
        let filePath = docPath.stringByAppendingPathComponent(fileName)
        let url = NSURL(fileURLWithPath: filePath)
        
        aUrl = url
        
        return try! AVAudioRecorder(URL: url, settings: setting)
    }
}
 
cs

반응형

댓글