Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import UIKit
  2. import AVFoundation
  3.  
  4.  
  5. class ZBSimleRecorder: NSObject {
  6.  
  7. var audioEngine: AVAudioEngine?
  8. var file: ExtAudioFileRef?
  9.  
  10. func start(fileURL:URL) {
  11. self.stop()
  12.  
  13. func M4aFormat() -> AudioStreamBasicDescription {
  14. return AudioStreamBasicDescription(mSampleRate: 44100,
  15. mFormatID: kAudioFormatMPEG4AAC,
  16. mFormatFlags: AudioFormatFlags(MPEG4ObjectID.aac_Main.rawValue),
  17. mBytesPerPacket: 0,
  18. mFramesPerPacket: 1024,
  19. mBytesPerFrame: 0,
  20. mChannelsPerFrame: 2,
  21. mBitsPerChannel: 0,
  22. mReserved: 0)
  23. }
  24.  
  25. audioEngine = AVAudioEngine()
  26. guard let audioEngine = audioEngine else {
  27. return
  28. }
  29.  
  30. let audioSession = AVAudioSession.sharedInstance()
  31. try? audioSession.setCategory(AVAudioSessionCategoryRecord)
  32. try? audioSession.setMode(AVAudioSessionModeVoiceChat)
  33. try? audioSession.setActive(true, with: .notifyOthersOnDeactivation)
  34.  
  35. guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") }
  36. let recordingFormat = inputNode.outputFormat(forBus: 0)
  37.  
  38. var outputFormat = M4aFormat()
  39. var status = noErr
  40. status = ExtAudioFileCreateWithURL(fileURL as CFURL, kAudioFileM4AType, &outputFormat, nil, AudioFileFlags.eraseFile.rawValue, &file)
  41. assert(status == noErr)
  42. var codecManufacturer = kAppleSoftwareAudioCodecManufacturer
  43. status = ExtAudioFileSetProperty(file!, kExtAudioFileProperty_CodecManufacturer, UInt32(MemoryLayout<UInt32>.size), &codecManufacturer)
  44. assert(status == noErr)
  45. status = ExtAudioFileSetProperty(file!, kExtAudioFileProperty_ClientDataFormat, UInt32(MemoryLayout<AudioStreamBasicDescription>.size), recordingFormat.streamDescription)
  46. assert(status == noErr)
  47.  
  48. inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
  49. let numberOfFrames = buffer.frameLength
  50. let audioBufferList = buffer.audioBufferList
  51. let status = ExtAudioFileWrite(self.file!, numberOfFrames, audioBufferList)
  52. assert(status == noErr)
  53. }
  54.  
  55. audioEngine.prepare()
  56. try? audioEngine.start()
  57. }
  58.  
  59. func stop() {
  60.  
  61. guard let audioEngine = audioEngine else {
  62. return
  63. }
  64.  
  65. let audioSession = AVAudioSession.sharedInstance()
  66. try? audioSession.setActive(false, with: .notifyOthersOnDeactivation)
  67.  
  68. if let file = file {
  69. ExtAudioFileDispose(file)
  70. self.file = nil
  71. }
  72.  
  73. audioEngine.stop()
  74.  
  75. }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement