使用Swift,录制并保存音频文件

来源:互联网 发布:更改信息sql语句 编辑:程序博客网 时间:2024/05/18 22:54
////  RecordSoundsViewController.swift//  PitchPerfect////  Created by Zzcz on 2017/9/27.//  Copyright © 2017年 fly. All rights reserved.//import UIKitimport AVFoundationclass RecordSoundsViewController: UIViewController {        @IBOutlet weak var recordButton: UIButton!    @IBOutlet weak var recordingLable: UILabel!    @IBOutlet weak var stopRecordingButton: UIButton!    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        stopRecordingButton.isEnabled = false    }    var audioRecorder : AVAudioRecorder!        @IBAction func recordAudio(_ sender: Any) {        recordingLable.text = "Recording in Progress"        stopRecordingButton.isEnabled = true        recordButton.isEnabled = false                let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String        let recordingName = "recordedVoive.wav"        let pathArray = [dirPath,recordingName]        let filePaht = URL(string: pathArray.joined(separator: "/"))                let session = AVAudioSession.sharedInstance()        try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker)                try! audioRecorder = AVAudioRecorder(url: filePaht!, settings: [:])        audioRecorder.delegate = self        audioRecorder.isMeteringEnabled = true        audioRecorder.prepareToRecord()        audioRecorder.record()            }    @IBAction func stopRecording(_ sender: Any) {            recordingLable.text = "Tap to Record"        recordButton.isEnabled = true        stopRecordingButton.isEnabled = false        audioRecorder.stop()        let audioSession = AVAudioSession.sharedInstance()        try! audioSession.setActive(false)        }    }extension RecordSoundsViewController : AVAudioRecorderDelegate {    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {        print("finished recording")    }}

原创粉丝点击