-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathKAudioRecorder.swift
231 lines (161 loc) · 6 KB
/
KAudioRecorder.swift
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
//
// KAudioRecorder
//
// Copyright © 2017 Kenan Atmaca. All rights reserved.
// kenanatmaca.com
//
//
import UIKit
import AVFoundation
class KAudioRecorder: NSObject {
static var shared = KAudioRecorder()
private var audioSession:AVAudioSession = AVAudioSession.sharedInstance()
private var audioRecorder:AVAudioRecorder!
private var audioPlayer:AVAudioPlayer = AVAudioPlayer()
private let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
fileprivate var timer:Timer!
var isPlaying:Bool = false
var isRecording:Bool = false
var url:URL?
var time:Int = 0
var recordName:String?
override init() {
super.init()
isAuth()
}
private func recordSetup() {
let newVideoName = getDir().appendingPathComponent(recordName?.appending(".m4a") ?? "sound.m4a")
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
audioRecorder = try AVAudioRecorder(url: newVideoName, settings: self.settings)
audioRecorder.delegate = self as AVAudioRecorderDelegate
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
} catch {
print("Recording update error:",error.localizedDescription)
}
}
func record() {
recordSetup()
if let recorder = self.audioRecorder {
if !isRecording {
do {
try audioSession.setActive(true)
time = 0
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
recorder.record()
isRecording = true
} catch {
print("Record error:",error.localizedDescription)
}
}
}
}
@objc private func updateTimer() {
if isRecording && !isPlaying {
time += 1
} else {
timer.invalidate()
}
}
func stop() {
audioRecorder.stop()
do {
try audioSession.setActive(false)
} catch {
print("stop()",error.localizedDescription)
}
}
func play() {
if !isRecording && !isPlaying {
if let recorder = self.audioRecorder {
if recorder.url.path == url?.path && url != nil {
audioPlayer.play()
return
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: recorder.url)
audioPlayer.delegate = self as AVAudioPlayerDelegate
url = audioRecorder.url
audioPlayer.play()
} catch {
print("play(), ",error.localizedDescription)
}
}
} else {
return
}
}
func play(name:String) {
let bundle = getDir().appendingPathComponent(name.appending(".m4a"))
if FileManager.default.fileExists(atPath: bundle.path) && !isRecording && !isPlaying {
do {
audioPlayer = try AVAudioPlayer(contentsOf: bundle)
audioPlayer.delegate = self as AVAudioPlayerDelegate
audioPlayer.play()
} catch {
print("play(with name:), ",error.localizedDescription)
}
} else {
return
}
}
func delete(name:String) {
let bundle = getDir().appendingPathComponent(name.appending(".m4a"))
let manager = FileManager.default
if manager.fileExists(atPath: bundle.path) {
do {
try manager.removeItem(at: bundle)
} catch {
print("delete()",error.localizedDescription)
}
} else {
print("File is not exist.")
}
}
func stopPlaying() {
audioPlayer.stop()
isPlaying = false
}
private func getDir() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths.first!
}
@discardableResult
func isAuth() -> Bool {
var result:Bool = false
AVAudioSession.sharedInstance().requestRecordPermission { (res) in
result = res == true ? true : false
}
return result
}
func getTime() -> String {
var result:String = ""
if time < 60 {
result = "\(time)"
} else if time >= 60 {
result = "\(time / 60):\(time % 60)"
}
return result
}
}//
extension KAudioRecorder: AVAudioRecorderDelegate {
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
isRecording = false
url = nil
timer.invalidate()
print("record finish")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print(error.debugDescription)
}
}
extension KAudioRecorder: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
isPlaying = false
print("playing finish")
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print(error.debugDescription)
}
}