Swift logo

Swift: Audioaufnahmen mit AVAudioRecorder

By

in

In Swift lassen sich Audioaufnahmen sehr komfortabel und einfach über die Klasse AVAudioRecorder realisieren. Beim Initialisieren der Klasse lassen sich bereits Codec, Samplerate, Anzahl der Kanäle und einige andere wichtige Einstellungen festlegen. Hier ein einfaches Code-Beispiel:

class AudioViewController : UIViewController, AVAudioRecorderDelegate
{
    // [...]
 
    var audioRecorder: AVAudioRecorder!
     
    func initAudioRecorder()
    {
        let settings: [String : Any] = [
            AVSampleRateKey: 16000.0,
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVNumberOfChannelsKey: 1,
            AVEncoderAudioQualityKey: AVAudioQuality.low.rawValue
        ]
         
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSessionCategoryRecord)
            try audioRecorder = AVAudioRecorder(url: getFileurl()!, settings: settings)
            try audioSession.setActive(true)
        }
        catch let error as NSError {
            print("AVAudioRecorder error: \(error.localizedDescription)")
        }
     
        audioRecorder.delegate = self
        audioRecorder.isMeteringEnabled = true
        audioRecorder.prepareToRecord()
         
        let displayLink:CADisplayLink = CADisplayLink(target: self, selector: #selector(updateMeters))
        displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
    }
     
    func updateMeters()
    {
        audioRecorder.updateMeters()
         
        if audioRecorder.isRecording
        {
            let time = NSInteger(audioRecorder.currentTime)
            // ...
        }
 
        // TOOD: do any updates e.g. for the UI (update displayed record time, ...)
    }
 
    @IBAction func startRecord(_ sender: AnyObject)
    {
        audioRecorder.record()
    }
 
    @IBAction func stopRecord(_ sender: AnyObject)
    {
        audioRecorder.stop()
    }
     
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool)
    {
        // Add audio to attachments
        let audioData = try? Data(contentsOf: getFileurl()!)
        if audioData != nil
        {
            // TOOD: handle audio data
        }
    }
     
    func getFileurl() -> URL?
    {
        let fileManager = FileManager.default
        let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
        let documentDirectory = urls[0] as URL
        let audioURL = documentDirectory.appendingPathComponent("audio.m4a")
         
        return audioURL
    }
}


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *