iOS 录音与播放

实现思路

利用系统框架AVFoundation实现录音和录音播放

注意事项

在Info.plist文件中添加如下代码:
Privacy - Microphone Usage Description

iOS 录音与播放_第1张图片
754EFE5A-2AC9-4AAA-B083-F3A4DC3B53A0.png

核心代码

1.添加框架
import AVFoundation

2.初始化录音器和播放器

    //录音器
    var audioRecorder:AVAudioRecorder!
    //播放器
    var audioPlayer:AVAudioPlayer!
    //获取音频会话单例
    let audioSession = AVAudioSession.sharedInstance()
    var filePath : String?
    
    /**
     定义音频的编码参数
     AVSampleRateKey:声音采样率 8000/11025/22050/44100/96000(影响音频的质量)
     AVFormatIDKey:编码格式
     AVLinearPCMBitDepthKey:采样位数  8、16、24、32 默认为16
     AVNumberOfChannelsKey:音频通道数 1 或 2
     AVEncoderAudioQualityKey:音频质量
     */
    let recordSettings = [AVSampleRateKey:NSNumber.init(value: 44100.0),AVFormatIDKey:NSNumber.init(value:kAudioFormatLinearPCM),AVLinearPCMBitDepthKey:NSNumber.init(value: 16),AVNumberOfChannelsKey:NSNumber.init(value: 1),AVEncoderAudioQualityKey:NSNumber.init(value:AVAudioQuality.high.rawValue)]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "录音"
        initRecorder()
    }
    
    func initRecorder() {
        
        do {
            try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
            //MARK:加这段代码解决声音很小的问题
            try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
            try audioRecorder = AVAudioRecorder(url: self.directoryUrl()! as URL, settings: recordSettings)
            audioRecorder.isMeteringEnabled = true
            audioRecorder.prepareToRecord()
            audioRecorder.delegate = self
        } catch let error as NSError {
            print(error)
        }
    }

    func directoryUrl () -> NSURL? {
         let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
         filePath = (path)! + "/Record.wav"
         let fileUrl = NSURL.init(fileURLWithPath: filePath!)
         return fileUrl
      }

3.开始录制

@IBAction func beginRecorder(_ sender: Any) {
        //如果正在播放,则停止播放
        if let audio = audioPlayer {
            if audio.isPlaying {
                audio.stop()
            }
        }
        
        if !audioRecorder.isRecording {
            do {
                try audioSession.setActive(true)
                audioRecorder.record()
            } catch let error as NSError {
                print(error)
            }
        }
    }

4.暂停录制

@IBAction func pauseRecorder(_ sender: Any) {
        //暂停后,点击开始录制则会继续接下去录制
        if audioRecorder.isRecording {
            audioRecorder.pause()
        }
    }

5.停止录制

@IBAction func stopRecorder(_ sender: Any) {
        
        if audioRecorder.isRecording {
            audioRecorder.stop()
            do {
                try audioSession.setActive(false)
            } catch let error as NSError {
                print(error)
            }
        }
    }

6.开始播放

@IBAction func startPlaying(_ sender: Any) {
        
        //计算录制文件的大小
        let manager = FileManager.default
        if manager.fileExists(atPath: filePath!) {
            do {
               let attr = try manager.attributesOfItem(atPath: filePath!)
                let size = attr[FileAttributeKey.size] as! Float
                print("文件大小为 \(size/1024.0)Kb")
            } catch let error as NSError {
                print(error)
            }
        }
        
        audioRecorder.stop()
        
        do {
            print(audioRecorder.url)
            let url:URL? = audioRecorder.url
            if let url = url {
                try audioPlayer = AVAudioPlayer.init(contentsOf: url)
                audioPlayer.delegate = self
                audioPlayer.play()
            }
        } catch let error as NSError {
            print(error)
        }
    }

7.暂停播放

@IBAction func pausePlaying(_ sender: Any) {
        
        if let player = audioPlayer {
            if player.isPlaying {
                if !audioRecorder.isRecording {
                    player.pause()
                }
            }
        }
    }

8.录音器和播放器的两个代理方法

extension ViewController : AVAudioRecorderDelegate {
    
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if flag {
            print("录制完成")
            
        }
    }
}

extension ViewController : AVAudioPlayerDelegate {
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            print("播放完成")
        }
    }
    
}

把所有代码整合一起就是一个Demo

你可能感兴趣的:(iOS 录音与播放)