Recording audio in Swift

后端 未结 8 1788
别那么骄傲
别那么骄傲 2020-12-04 06:12

Does anyone know where I can find info on how to record audio in a Swift application? I\'ve been looking at some of the audio playback examples but I can\'t seem to be able

相关标签:
8条回答
  • 2020-12-04 07:02

    In addition to previous answers, I tried to make it work on Xcode 7.2 and I couldn't hear any sound after, neither when I sent the file via email. No warning or exception. So I changed settings to the following and stored as an .m4a file.

    let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
        AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
        AVNumberOfChannelsKey : NSNumber(int: 1),
        AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue))]
    

    After that I could listen to sound. For saving the file, I added this on viewDidLoad to initialise the recorder:

    let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
            try audioRecorder = AVAudioRecorder(URL: self.directoryURL()!,
                settings: recordSettings)
            audioRecorder.prepareToRecord()
        } catch {
        }
    

    And for creating the directory:

    func directoryURL() -> NSURL? {
        let fileManager = NSFileManager.defaultManager()
        let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let documentDirectory = urls[0] as NSURL
        let soundURL = documentDirectory.URLByAppendingPathComponent("sound.m4a")
        return soundURL 
    }
    

    I also add the actions used to start recording, stop, and play after

    @IBAction func doRecordAction(sender: AnyObject) {
        if !audioRecorder.recording {
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(true)
                audioRecorder.record()
            } catch {
            }
       }
    }
    @IBAction func doStopRecordingAction(sender: AnyObject) {
        audioRecorder.stop()
        let audioSession = AVAudioSession.sharedInstance()
    
        do {
            try audioSession.setActive(false)
        } catch {
        }
    }
    
    @IBAction func doPlayAction(sender: AnyObject) {
        if (!audioRecorder.recording){
            do {
                try audioPlayer = AVAudioPlayer(contentsOfURL: audioRecorder.url)
                audioPlayer.play()
            } catch {
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 07:11

    Here audio recorder with simple interface written on Swift 4.2 .

    final class AudioRecorderImpl: NSObject {
      private let session = AVAudioSession.sharedInstance()
      private var player: AVAudioPlayer?
      private var recorder: AVAudioRecorder?
      private lazy var permissionGranted = false
      private lazy var isRecording = false
      private lazy var isPlaying = false
      private var fileURL: URL?
      private let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 44100,
        AVNumberOfChannelsKey: 2,
        AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
      ]
    
      override init() {
        fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("note.m4a")
      }
    
      func record(to url: URL?) {
        guard permissionGranted,
          let url = url ?? fileURL else { return }
    
        setupRecorder(url: url)
    
        if isRecording {
          stopRecording()
        }
    
        isRecording = true
        recorder?.record()
      }
    
      func stopRecording() {
        isRecording = false
        recorder?.stop()
        try? session.setActive(false)
      }
    
      func play(from url: URL?) {
        guard let url = url ?? fileURL else { return }
    
        setupPlayer(url: url)
    
        if isRecording {
          stopRecording()
        }
    
        if isPlaying {
          stopPlaying()
        }
    
        if FileManager.default.fileExists(atPath: url.path) {
          isPlaying = true
          setupPlayer(url: url)
          player?.play()
        }
      }
    
      func stopPlaying() {
        player?.stop()
      }
    
      func pause() {
        player?.pause()
      }
    
      func resume() {
        if player?.isPlaying == false {
          player?.play()
        }
      }
    
      func checkPermission(completion: ((Bool) -> Void)?) {
        func assignAndInvokeCallback(_ granted: Bool) {
          self.permissionGranted = granted
          completion?(granted)
        }
    
        switch session.recordPermission {
        case .granted:
          assignAndInvokeCallback(true)
    
        case .denied:
          assignAndInvokeCallback(false)
    
        case .undetermined:
          session.requestRecordPermission(assignAndInvokeCallback)
        }
      }
    }
    
    extension AudioRecorderImpl: AVAudioRecorderDelegate, AVAudioPlayerDelegate {
    
    }
    
    private extension AudioRecorderImpl {
      func setupRecorder(url: URL) {
        guard
          permissionGranted else { return }
        try? session.setCategory(.playback, mode: .default)
        try? session.setActive(true)
        let settings = [
          AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
          AVSampleRateKey: 44100,
          AVNumberOfChannelsKey: 2,
          AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]
        recorder = try? AVAudioRecorder(url: url, settings: settings)
        recorder?.delegate = self
        recorder?.isMeteringEnabled = true
        recorder?.prepareToRecord()
      }
    
      func setupPlayer(url: URL) {
        player = try? AVAudioPlayer(contentsOf: url)
        player?.delegate = self
        player?.prepareToPlay()
      }
    }
    
    0 讨论(0)
提交回复
热议问题