Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. ##錄音
  2.  
  3. import Foundation
  4. import AVFoundation
  5.  
  6. enum AudioSessionMode{
  7. case reocrd
  8. case play
  9. }
  10.  
  11. class RecordHelper:NSObject, AVAudioRecorderDelegate{
  12.  
  13. var audioRecorder:AVAudioRecorder?
  14. var audioPlayer:AVAudioPlayer?
  15. var isRecording = false
  16.  
  17.  
  18. override init() {
  19. super.init()
  20. // init an audio recorder
  21. //錄音檔名
  22. let fileName = "User.wav"
  23. //檔案總目錄
  24. let path = NSHomeDirectory() + "/Documents" + fileName
  25. let url = URL(fileURLWithPath: path)
  26. let recordSettings:[String:Any] = [
  27. //錄音品質
  28. AVEncoderAudioQualityKey:AVAudioQuality.min.rawValue,
  29. AVEncoderBitRateKey:16,
  30. AVNumberOfChannelsKey:2,
  31. //取樣品質
  32. AVSampleRateKey:44100.0
  33. ]
  34.  
  35. do {
  36. self.audioRecorder = try AVAudioRecorder(url: url, settings: recordSettings)
  37. self.audioRecorder?.delegate = self
  38.  
  39. } catch {
  40. print(error.localizedDescription)
  41. }
  42.  
  43. }
  44.  
  45.  
  46. //音訊工作階段
  47. func settingAudioSession(mode:AudioSessionMode){
  48. //取得音訊工作階段
  49. let session = AVAudioSession.sharedInstance()
  50. do {
  51. switch mode {
  52. case .reocrd:
  53. try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
  54. case .play:
  55. try session.setCategory(AVAudioSessionCategoryPlayback)
  56. try session.setActive(false)
  57. }
  58. } catch{
  59. print(error.localizedDescription)
  60. }
  61. }
  62.  
  63.  
  64. func recordAudio() {
  65. settingAudioSession(mode: .reocrd)
  66. self.audioRecorder?.prepareToRecord()
  67. self.audioRecorder?.record()
  68. isRecording = true
  69. }
  70.  
  71. func stopAudio() {
  72. self.audioRecorder?.stop()
  73. isRecording = false
  74. settingAudioSession(mode: .play)
  75. }
  76.  
  77. func playAudio() {
  78. if isRecording == false {
  79. self.audioPlayer?.stop()
  80. self.audioPlayer?.currentTime = 0.0
  81. self.audioPlayer?.play()
  82. }
  83. }
  84.  
  85. func stopPlayAudio() {
  86. if isRecording == false {
  87. self.audioPlayer?.stop()
  88. self.audioPlayer?.currentTime = 0.0
  89. }
  90. }
  91.  
  92.  
  93.  
  94. func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
  95. if flag == true {
  96. do {
  97. self.audioPlayer = try AVAudioPlayer(contentsOf: recorder.url)
  98. } catch {
  99. print(error.localizedDescription)
  100. }
  101. }
  102. }
  103.  
  104.  
  105.  
  106.  
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement