swift 录音及播放工具类

注释:因项目需求,需要开发录音功能,所以在网上找到工具类并做了Demo,具体实现的细节还需优化!

*此工具类包含 录音的开始,停止,播放功能

import Foundation
import AVFoundation

class RecordManager{
    var recorder:AVAudioRecorder?
    var player : AVAudioPlayer?
    let file_path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/record")
    //开始录音
    func beginRecord() {
        let session = AVAudioSession.sharedInstance()
        do{
            try session.setCategory(AVAudioSession.Category.playAndRecord)
        } catch let err{
            print("设置类型失败:\(err.localizedDescription)")
        }
        
        //设置session动作
        do {
            try session.setActive(true)
        } catch let err {
            print("初始化动作失败:\(err.localizedDescription)")
        }
        
        //录音设置,注意,后面需要转换成NSNumber,如果不转换,你会发现,无法录制音频文件,
        let recordSetting:[String:Any] = [AVSampleRateKey:NSNumber(value:16000),//采样集
            AVFormatIDKey:NSNumber(value: kAudioFormatLinearPCM),//音频格式
            AVLinearPCMBitDepthKey:NSNumber(value:16),//采样位数
            AVNumberOfChannelsKey:NSNumber(value: 1),//通道数
            AVEncoderAudioQualityKey:NSNumber(value: AVAudioQuality.min.rawValue)//录音质量
        ]
        
        //开始录音
        do {
            let url = URL(fileURLWithPath: file_path!)
            recorder = try AVAudioRecorder(url: url, settings: recordSetting)
            recorder!.prepareToRecord()
            recorder!.record()
            print("开始录音")
        } catch let err {
            print("录音失败:\(err.localizedDescription)")
        }
    }
    
    //结束录音
    func stopRecord() {
        if let recorder = self.recorder{
            if recorder.isRecording {
                print("正在录音,马上结束它,文件保存到了:\(file_path!)")
            }else{
                print("没有录音,但是依然结束它")
            }
            recorder.stop()
            self.recorder = nil
        }else{
            print("没有初始化")
        }
    }
    
    //播放
    func play() {
        do {
            player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: file_path!))
            print("歌曲长度:\(player!.duration)")
            player!.play()
            
        } catch let err {
            print("播放失败:\(err.localizedDescription)")
        }
    }
}

你可能感兴趣的:(swift 录音及播放工具类)