ios – AVAudioRecorder记录流音频

前端之家收集整理的这篇文章主要介绍了ios – AVAudioRecorder记录流音频前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个播放流音频的应用程序.如何使用AVAudioRecorder(或其他东西?)从AVPlayer录制流式音频.谢谢.

解决方法

斯威夫特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
        }
    }
}
原文链接:/iOS/331533.html

猜你在找的iOS相关文章