Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##錄音
- import Foundation
- import AVFoundation
- enum AudioSessionMode{
- case reocrd
- case play
- }
- class RecordHelper:NSObject, AVAudioRecorderDelegate{
- var audioRecorder:AVAudioRecorder?
- var audioPlayer:AVAudioPlayer?
- var isRecording = false
- override init() {
- super.init()
- // init an audio recorder
- //錄音檔名
- let fileName = "User.wav"
- //檔案總目錄
- let path = NSHomeDirectory() + "/Documents" + fileName
- let url = URL(fileURLWithPath: path)
- let recordSettings:[String:Any] = [
- //錄音品質
- AVEncoderAudioQualityKey:AVAudioQuality.min.rawValue,
- AVEncoderBitRateKey:16,
- AVNumberOfChannelsKey:2,
- //取樣品質
- AVSampleRateKey:44100.0
- ]
- do {
- self.audioRecorder = try AVAudioRecorder(url: url, settings: recordSettings)
- self.audioRecorder?.delegate = self
- } catch {
- print(error.localizedDescription)
- }
- }
- //音訊工作階段
- func settingAudioSession(mode:AudioSessionMode){
- //取得音訊工作階段
- let session = AVAudioSession.sharedInstance()
- do {
- switch mode {
- case .reocrd:
- try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
- case .play:
- try session.setCategory(AVAudioSessionCategoryPlayback)
- try session.setActive(false)
- }
- } catch{
- print(error.localizedDescription)
- }
- }
- func recordAudio() {
- settingAudioSession(mode: .reocrd)
- self.audioRecorder?.prepareToRecord()
- self.audioRecorder?.record()
- isRecording = true
- }
- func stopAudio() {
- self.audioRecorder?.stop()
- isRecording = false
- settingAudioSession(mode: .play)
- }
- func playAudio() {
- if isRecording == false {
- self.audioPlayer?.stop()
- self.audioPlayer?.currentTime = 0.0
- self.audioPlayer?.play()
- }
- }
- func stopPlayAudio() {
- if isRecording == false {
- self.audioPlayer?.stop()
- self.audioPlayer?.currentTime = 0.0
- }
- }
- func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
- if flag == true {
- do {
- self.audioPlayer = try AVAudioPlayer(contentsOf: recorder.url)
- } catch {
- print(error.localizedDescription)
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement