Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Capturing Audio
- First, we need import the __AVFoundation__ framework.
- ```swift
- import AVFoundation
- ```
- Secondly, we should have a global variable to hold __AVAudioRecorder__ instance. We will initialize it later.
- ```swift
- var audioRecorder: AVAudioRecorder!
- ```
- To capture a sound we will use a shared instance of __AVAudioSession__.
- ```swift
- let session = AVAudioSession.sharedInstance()
- try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker)
- ```
- Before start capturing audio, let's create a URL to save our recorded audio file.
- ```swift
- let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
- let recordingName = "recordedVoice.wav"
- let pathArray = [dirPath, recordingName]
- let filePath = URL(string: pathArray.joined(separator: "/"))
- ```
- Now, do the work!
- ```swift
- // Initialize the recorder
- try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
- // Make metering for audio is enabled
- audioRecorder.isMeteringEnabled = true
- // Create the file and make system ready to record
- audioRecorder.prepareToRecord()
- // Go, go, go!
- audioRecorder.record()
- ```
- To stop the recording
- ```swift
- audioRecorder.stop()
- let audioSession = AVAudioSession.sharedInstance()
- audioSession.setActive(false)
- ```
Add Comment
Please, Sign In to add comment