在Swift中录制音频并在其他视图中播放

时间:2019-05-01 07:27:30

标签: ios swift avaudiorecorder

我能够记录声音并在同一视图中播放声音,但是当我尝试将音频URL传递到其他视图时,发现发生了recorder: AVAudioRecorder URL专家,当音频停止记录时,我正在传递filePath

func recoderAudio() {
        let recoderSettings = [AVFormatIDKey:kAudioFormatAppleLossless,
                               AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
                               AVEncoderBitRateKey:32000,
                               AVNumberOfChannelsKey:2,
                               AVSampleRateKey:44100.0] as [String : Any]
        let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String
        let recordingName = "recordedVoice.m4p"
        let pathArray = [dirPath, recordingName]
        self.filePath = URL(string: pathArray.joined(separator: "/"))
        do {
            audioRecorder = try AVAudioRecorder (url: filePath!, settings: recoderSettings)
            audioRecorder.delegate = self
            audioRecorder.prepareToRecord()
            audioRecorder.record()
        } catch {
            print(error.localizedDescription)
        }
    }

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        let popupVC = self.getStoryBoard().instantiateViewController(withIdentifier: "PlayAudio") as! PlayAudio
        popupVC.filePath = recorder.url
        print ("recorder.url \(recorder.url)")
        showPopUp(popupVC, parent: self)
    }



func playSound() {
        do {
            var soundPlayer : AVAudioPlayer!
            soundPlayer = try AVAudioPlayer(contentsOf: filePath!)
            soundPlayer.delegate  = self
            soundPlayer.prepareToPlay()
            soundPlayer.volume = 1.0
            soundPlayer.play()
        } catch {
            print(error.localizedDescription)
        }
    }

0 个答案:

没有答案