簡體   English   中英

AVAudioRecorder記錄流音頻

[英]AVAudioRecorder record stream audio

我有一個播放流音頻的應用程序。 如何使用AVAudioRecorder(或其他東西?)從AVPlayer錄制流式音頻。 謝謝。

Swift 3+這里是簡單的VC,可以將音頻會話保存到文件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
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM