質問編集履歴

1

追記

2020/03/23 11:30

投稿

R3.S
R3.S

スコア44

test CHANGED
File without changes
test CHANGED
@@ -165,3 +165,187 @@
165
165
 
166
166
 
167
167
  よろしくお願い致します。
168
+
169
+
170
+
171
+ ### 追記
172
+
173
+ ```ここに言語を入力
174
+
175
+ import UIKit
176
+
177
+ import AVFoundation
178
+
179
+
180
+
181
+ class ViewController: UIViewController {
182
+
183
+
184
+
185
+
186
+
187
+ @IBOutlet weak var recordLebal: UILabel!
188
+
189
+
190
+
191
+ var audioRecorder: AVAudioRecorder!
192
+
193
+ var audioEngine: AVAudioEngine!
194
+
195
+ var audioFile: AVAudioFile!
196
+
197
+ var audioPlayerNode: AVAudioPlayerNode!
198
+
199
+
200
+
201
+ override func viewDidLoad() {
202
+
203
+ super.viewDidLoad()
204
+
205
+
206
+
207
+ let session = AVAudioSession.sharedInstance()
208
+
209
+
210
+
211
+ do {
212
+
213
+ try session.setCategory(.playAndRecord, mode: .default)
214
+
215
+ try session.setActive(true)
216
+
217
+
218
+
219
+ let settings = [
220
+
221
+ AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
222
+
223
+ AVSampleRateKey: 44100,
224
+
225
+ AVNumberOfChannelsKey: 2,
226
+
227
+ AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
228
+
229
+ ]
230
+
231
+
232
+
233
+ audioRecorder = try AVAudioRecorder(url: getAudioFileUrl(), settings: settings)
234
+
235
+ audioRecorder.delegate = self as? AVAudioRecorderDelegate
236
+
237
+ } catch let error {
238
+
239
+ print(error)
240
+
241
+ }
242
+
243
+
244
+
245
+ }
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+ @IBAction func record(_ sender: Any) {
254
+
255
+
256
+
257
+ if !audioRecorder.isRecording {
258
+
259
+ audioRecorder.record(forDuration: 15)
260
+
261
+ recordLebal.text = "録音中"
262
+
263
+ } else {
264
+
265
+ audioRecorder.stop()
266
+
267
+ recordLebal.text = "録音終了"
268
+
269
+ }
270
+
271
+
272
+
273
+
274
+
275
+ }
276
+
277
+
278
+
279
+
280
+
281
+
282
+
283
+ @IBAction func play(_ sender: Any) {
284
+
285
+ audioEngine = AVAudioEngine()
286
+
287
+ do {
288
+
289
+ audioFile = try AVAudioFile(forReading: getAudioFileUrl())
290
+
291
+
292
+
293
+ audioPlayerNode = AVAudioPlayerNode()
294
+
295
+ audioEngine.attach(audioPlayerNode)
296
+
297
+ audioEngine.connect(audioPlayerNode, to: audioEngine.outputNode, format: audioFile.processingFormat)
298
+
299
+
300
+
301
+ audioPlayerNode.stop()
302
+
303
+ audioPlayerNode.scheduleFile(audioFile, at: nil)
304
+
305
+
306
+
307
+ try audioEngine.start()
308
+
309
+ audioPlayerNode.play()
310
+
311
+ } catch let error {
312
+
313
+ print(error)
314
+
315
+ }
316
+
317
+ recordLebal.text = "再生中"
318
+
319
+
320
+
321
+ }
322
+
323
+
324
+
325
+
326
+
327
+
328
+
329
+
330
+
331
+
332
+
333
+ func getAudioFileUrl() -> URL {
334
+
335
+ let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
336
+
337
+ let docsDirect = paths[0]
338
+
339
+ let audioUrl = docsDirect.appendingPathComponent("recording.m4a")
340
+
341
+
342
+
343
+ return audioUrl
344
+
345
+ }
346
+
347
+ }
348
+
349
+
350
+
351
+ ```