>

Swift 애플리케이션에서 오디오를 녹음하는 방법에 대한 정보를 어디서 찾을 수 있는지 아는 사람이 있습니까? 오디오 재생 예제 중 일부를 살펴 봤지만 오디오 레코딩 구현에 대한 내용을 찾을 수없는 것 같습니다. 감사합니다

  • 답변 # 1

    여기에 코드가 있습니다. 쉽게 녹음 할 수 있습니다 . IBAction 에서이 코드를 작성하십시오 그것은 Documents 에 기록을 저장합니다  이름으로 recordTest.caf

    //declare instance variable 
    var audioRecorder:AVAudioRecorder!
    func record(){        
        var audioSession:AVAudioSession = AVAudioSession.sharedInstance()
        audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
        audioSession.setActive(true, error: nil)
        var documents: AnyObject = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true)[0]
        var str =  documents.stringByAppendingPathComponent("recordTest.caf")
        var url = NSURL.fileURLWithPath(str as String)
        var recordSettings = [AVFormatIDKey:kAudioFormatAppleIMA4,
            AVSampleRateKey:44100.0,
            AVNumberOfChannelsKey:2,AVEncoderBitRateKey:12800,
            AVLinearPCMBitDepthKey:16,
            AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue]
        println("url : \(url)")
        var error: NSError?
        audioRecorder = AVAudioRecorder(URL:url, settings: recordSettings, error: &error)
        if let e = error {
            println(e.localizedDescription)
        } else {
            audioRecorder.record()
        }        
    }
    
    

  • 답변 # 2

    Swift 3에서

    프레임 워크 AVFoundation 추가

    ** info.plist에서 키 값 추가

    와이즈 비즈

    (값을 제공하지 않으면 앱이 다운 됨-권한을 요청하는 이유 설명) **

    AVFoundation 및 AVAudioRecorderDelegate, AVAudioPlayerDelegate 가져 오기

    Key= Privacy - Microphone Usage Description and Value= For using microphone

    오디오 녹음 및 오디오 재생을위한 생성 버튼 및 디스플레이 레코딩 타이밍 레이블을 지정하고 콘센트 및 동작을 start_recording, play_recording으로 지정하고 나중에 사용할 변수를 선언합니다

    import AVFoundation
     class RecordVC: UIViewController , AVAudioRecorderDelegate, AVAudioPlayerDelegate
    
    

    viewDidLoad 기록 확인 권한

    @IBOutlet var recordingTimeLabel: UILabel!
    @IBOutlet var record_btn_ref: UIButton!
    @IBOutlet var play_btn_ref: UIButton!
    var audioRecorder: AVAudioRecorder!
    var audioPlayer : AVAudioPlayer!
    var meterTimer:Timer!
    var isAudioRecordingGranted: Bool!
    var isRecording = false
    var isPlaying = false
    
    

    녹화를 myRecording.m4a로 저장하려는 경로 생성

    override func viewDidLoad() {
        super.viewDidLoad()
        check_record_permission()
    }
    func check_record_permission()
    {
        switch AVAudioSession.sharedInstance().recordPermission() {
        case AVAudioSessionRecordPermission.granted:
            isAudioRecordingGranted = true
            break
        case AVAudioSessionRecordPermission.denied:
            isAudioRecordingGranted = false
            break
        case AVAudioSessionRecordPermission.undetermined:
            AVAudioSession.sharedInstance().requestRecordPermission({ (allowed) in
                    if allowed {
                        self.isAudioRecordingGranted = true
                    } else {
                        self.isAudioRecordingGranted = false
                    }
            })
            break
        default:
            break
        }
    }
    
    

    레코더 설정

    func getDocumentsDirectory() -> URL
    {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }
    func getFileUrl() -> URL
    {
        let filename = "myRecording.m4a"
        let filePath = getDocumentsDirectory().appendingPathComponent(filename)
    return filePath
    }
    
    

    버튼 start_recording으로 녹화 시작 updateAudioMeter를 사용하여 초를 누르고 표시하고 녹화가 시작되면 녹화를 마칩니다

    func setup_recorder()
    {
        if isAudioRecordingGranted
        {
            let session = AVAudioSession.sharedInstance()
            do
            {
                try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
                try session.setActive(true)
                let settings = [
                    AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                    AVSampleRateKey: 44100,
                    AVNumberOfChannelsKey: 2,
                    AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
                ]
                audioRecorder = try AVAudioRecorder(url: getFileUrl(), settings: settings)
                audioRecorder.delegate = self
                audioRecorder.isMeteringEnabled = true
                audioRecorder.prepareToRecord()
            }
            catch let error {
                display_alert(msg_title: "Error", msg_desc: error.localizedDescription, action_title: "OK")
            }
        }
        else
        {
            display_alert(msg_title: "Error", msg_desc: "Don't have access to use your microphone.", action_title: "OK")
        }
    }
    
    

    녹음 재생

    @IBAction func start_recording(_ sender: UIButton)
    {
        if(isRecording)
        {
            finishAudioRecording(success: true)
            record_btn_ref.setTitle("Record", for: .normal)
            play_btn_ref.isEnabled = true
            isRecording = false
        }
        else
        {
            setup_recorder()
            audioRecorder.record()
            meterTimer = Timer.scheduledTimer(timeInterval: 0.1, target:self, selector:#selector(self.updateAudioMeter(timer:)), userInfo:nil, repeats:true)
            record_btn_ref.setTitle("Stop", for: .normal)
            play_btn_ref.isEnabled = false
            isRecording = true
        }
    }
    func updateAudioMeter(timer: Timer)
    {
        if audioRecorder.isRecording
        {
            let hr = Int((audioRecorder.currentTime / 60) / 60)
            let min = Int(audioRecorder.currentTime / 60)
            let sec = Int(audioRecorder.currentTime.truncatingRemainder(dividingBy: 60))
            let totalTimeString = String(format: "%02d:%02d:%02d", hr, min, sec)
            recordingTimeLabel.text = totalTimeString
            audioRecorder.updateMeters()
        }
    }
    func finishAudioRecording(success: Bool)
    {
        if success
        {
            audioRecorder.stop()
            audioRecorder = nil
            meterTimer.invalidate()
            print("recorded successfully.")
        }
        else
        {
            display_alert(msg_title: "Error", msg_desc: "Recording failed.", action_title: "OK")
        }
    }
    
    

    녹음이 완료되면 재생 버튼을 활성화하고 재생이 끝나면 기록 버튼을 활성화합니다

    func prepare_play()
    {
        do
        {
            audioPlayer = try AVAudioPlayer(contentsOf: getFileUrl())
            audioPlayer.delegate = self
            audioPlayer.prepareToPlay()
        }
        catch{
            print("Error")
        }
    }
    @IBAction func play_recording(_ sender: Any)
    {
        if(isPlaying)
        {
            audioPlayer.stop()
            record_btn_ref.isEnabled = true
            play_btn_ref.setTitle("Play", for: .normal)
            isPlaying = false
        }
        else
        {
            if FileManager.default.fileExists(atPath: getFileUrl().path)
            {
                record_btn_ref.isEnabled = false
                play_btn_ref.setTitle("pause", for: .normal)
                prepare_play()
                audioPlayer.play()
                isPlaying = true
            }
            else
            {
                display_alert(msg_title: "Error", msg_desc: "Audio file is missing.", action_title: "OK")
            }
        }
    }
    
    

    디스플레이 알림 기능 일반화

    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool)
    {
        if !flag
        {
            finishAudioRecording(success: false)
        }
        play_btn_ref.isEnabled = true
    }
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
    {
        record_btn_ref.isEnabled = true
    }
    
    

  • 답변 # 3

    @codester의 답변의 Swift2 버전

    func display_alert(msg_title : String , msg_desc : String ,action_title : String)
    {
        let ac = UIAlertController(title: msg_title, message: msg_desc, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: action_title, style: .default)
        {
            (result : UIAlertAction) -> Void in
        _ = self.navigationController?.popViewController(animated: true)
        })
        present(ac, animated: true)
    }
    
    

  • 답변 # 4

    이전 답변 외에도 Xcode 7.2에서 작동하도록 만들려고했는데 이메일을 통해 파일을 보낼 때도 소리가 들리지 않습니다. 경고 나 예외가 없습니다. 그래서 설정을 다음과 같이 변경하고 .m4a 파일로 저장했습니다.

    func record() {
        //init
        let audioSession:AVAudioSession = AVAudioSession.sharedInstance()
        //ask for permission
        if (audioSession.respondsToSelector("requestRecordPermission:")) {
            AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
                if granted {
                    print("granted")
                    //set category and activate recorder session
                    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                    try! audioSession.setActive(true)
    
                    //get documnets directory
                    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
                    let fullPath = documentsDirectory.stringByAppendingPathComponent("voiceRecording.caf")
                    let url = NSURL.fileURLWithPath(fullPath)
                    //create AnyObject of settings
                    let settings: [String : AnyObject] = [
                        AVFormatIDKey:Int(kAudioFormatAppleIMA4), //Int required in Swift2
                        AVSampleRateKey:44100.0,
                        AVNumberOfChannelsKey:2,
                        AVEncoderBitRateKey:12800,
                        AVLinearPCMBitDepthKey:16,
                        AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue
                    ]
                    //record
                    try! self.audioRecorder = AVAudioRecorder(URL: url, settings: settings)
                } else{
                    print("not granted")
                }
            })
        }
    }
    
    

    그 후 나는 소리를들을 수 있었다. 파일을 저장하기 위해 viewDidLoad에 이것을 추가하여 레코더를 초기화했습니다.

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

    디렉토리 만들기 :

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

    또한 녹음 시작, 중지 및 이후 재생에 사용되는 동작을 추가

    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 
    }
    
    

  • 답변 # 5

    Swift 4.2에 작성된 간단한 인터페이스가있는 오디오 레코더

    @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 {
            }
        }
    }
    
    

    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() } }

  • 이전 javascript - redux에서 작업이 완료된 후 데이터를 가져 오는 방법은 무엇입니까?
  • 다음 mod perl2 - modperl - : registry로 실행 한 cgi 스크립트는 html 페이지에 결과를 인쇄하지 않고 다운로드 만합니다