Guest User

Untitled

a guest
Nov 17th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. # Capturing Audio
  2.  
  3. First, we need import the __AVFoundation__ framework.
  4.  
  5. ```swift
  6. import AVFoundation
  7. ```
  8.  
  9. Secondly, we should have a global variable to hold __AVAudioRecorder__ instance. We will initialize it later.
  10. ```swift
  11. var audioRecorder: AVAudioRecorder!
  12. ```
  13.  
  14. To capture a sound we will use a shared instance of __AVAudioSession__.
  15. ```swift
  16. let session = AVAudioSession.sharedInstance()
  17. try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker)
  18. ```
  19.  
  20. Before start capturing audio, let's create a URL to save our recorded audio file.
  21. ```swift
  22. let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
  23. let recordingName = "recordedVoice.wav"
  24. let pathArray = [dirPath, recordingName]
  25. let filePath = URL(string: pathArray.joined(separator: "/"))
  26. ```
  27.  
  28. Now, do the work!
  29. ```swift
  30. // Initialize the recorder
  31. try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
  32. // Make metering for audio is enabled
  33. audioRecorder.isMeteringEnabled = true
  34. // Create the file and make system ready to record
  35. audioRecorder.prepareToRecord()
  36. // Go, go, go!
  37. audioRecorder.record()
  38. ```
  39.  
  40. To stop the recording
  41. ```swift
  42. audioRecorder.stop()
  43. let audioSession = AVAudioSession.sharedInstance()
  44. audioSession.setActive(false)
  45. ```
Add Comment
Please, Sign In to add comment