简体   繁体   中英

AVAudioRecorder record stream audio

I have an app that playing stream audio. How can I record streaming audio from AVPlayer using AVAudioRecorder (or something another?). Thanks.

Swift 3+ Here is simple VC which will save audio session to documents dir (audio.aac)

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioRecorder: AVAudioRecorder?

    override func viewDidLoad() {
        super.viewDidLoad()
        verifyRecordPermission()
    }

    @IBAction func recordButonAction(_ sender: UIButton) {
        if audioRecorder?.isRecording == true {
            audioRecorder?.stop()
            sender.setTitle("Record", for: .normal)
        }
        else {
            startRecording()
            sender.setTitle("Stop", for: .normal)
        }
    }

    func verifyRecordPermission() {
        let permission = AVAudioSession.sharedInstance().recordPermission()
        switch permission {
        case .denied:
            print("recording not allowed")
        case .granted:
            print("recording allowed")
        default:
            AVAudioSession.sharedInstance().requestRecordPermission() { (granted) -> Void in
                print("recording granted:\(granted)")
            }
        }
    }

    func startRecording() {
        guard AVAudioSession.sharedInstance().recordPermission() == .granted else {
            return
        }

        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let audioUrl = URL(fileURLWithPath: "\(documentsPath)/audio.aac")
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(AVAudioSessionCategoryRecord)
            try session.setActive(true)
            try audioRecorder = AVAudioRecorder(url: audioUrl,
                                                settings: [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                                                           AVSampleRateKey: 24000.0,
                                                           AVNumberOfChannelsKey: 1 as NSNumber,
                                                           AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue])
        } catch {
            // handle error...
            return
        }

        guard let audioRecorder = audioRecorder else {
            return

        }
        audioRecorder.prepareToRecord()
        audioRecorder.record()
    }

    func stop(session: AVAudioSession = AVAudioSession.sharedInstance()) {
        audioRecorder?.stop()
        audioRecorder = nil
        do {
            try session.setActive(false)
        } catch {
            // handle session errors
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM