生活随笔
收集整理的這篇文章主要介紹了
swift5 实现录音App
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
swift5 實現錄音App
import UIKit
import AudioToolbox
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {var player
: AVAudioPlayer!var recorder
: AVAudioRecorder!var recordFileName
= ""override func viewDidLoad() {super.viewDidLoad()myLabel
.text
= "錄音測試"debugPrint(NSHomeDirectory())}override func prepare(for segue
: UIStoryboardSegue, sender
: Any?) {if player
!= nil {player
.stop()player
= nil}startButton
.isEnabled
= true}@IBOutlet weak var startButton
: UIButton!@IBOutlet weak var myLabel
: UILabel!@IBAction func addSound(_ sender
: UIButton) {sender
.isSelected
= !sender
.isSelected
if sender
.isSelected
{sender
.setTitle("結束并保存", for: .selected
)let alertController
= UIAlertController(title
: "文件名", message
: "請輸入錄音文件名", preferredStyle
: .alert
)let ensureAction
= UIAlertAction(title
: "確定", style
: .default) { (action
) inlet textField
= alertController
.textFields
![0] as UITextFieldself.recordFileName
= textField
.text
!self.createRecord()}let cancelAction
= UIAlertAction(title
: "取消", style
: .default, handler
: nil)alertController
.addAction(ensureAction
)alertController
.addAction(cancelAction
)alertController
.addTextField
{ (textField
) intextField
.placeholder
= "請輸入錄音文件名"}present(alertController
, animated
: true, completion
: nil)}else {saveRecord()}}@IBAction func startTest(_ sender
: UIButton) {sender
.isEnabled
= falseavPlaySound()}}
extension ViewController {func playSound() {let audioFilePath
= Bundle.main
.path(forResource
: fileName(), ofType
: nil)let url
= URL(fileURLWithPath
: audioFilePath
!)var soundID
: SystemSoundID = 0AudioServicesCreateSystemSoundID(url
as CFURL, &soundID
)AudioServicesPlaySystemSound(soundID
)AudioServicesPlaySystemSoundWithCompletion(soundID
) {print("AudioServices - 播放結束---")DispatchQueue.main
.asyncAfter(deadline
: DispatchTime.now() + 5, execute
: {print("AudioServices - 播放開始---")self.playSound()})}}
}
extension ViewController {func avPlaySound() {let audioFilePath
= Bundle.main
.path(forResource
: fileName(), ofType
: nil)let url
= URL(fileURLWithPath
: audioFilePath
!)player
= try? AVAudioPlayer(contentsOf
: url
)guard let p
= player
else {return}p
.delegate
= selfp
.play()}func audioPlayerDidFinishPlaying(_ player
: AVAudioPlayer, successfully flag
: Bool) {print("AVAudioPlayer - 播放結束---")DispatchQueue.main
.asyncAfter(deadline
: DispatchTime.now() + 5) {print("AVAudioPlayer - 播放開始---")guard self.player
!= nil else{return}self.avPlaySound()}}
}
extension ViewController {func fileName() -> String {let number
= arc4random_uniform(60)var fileName
= ""switch number
{case 0...9:fileName
= "diSound.wav"case 10...19:fileName
= "diSound.wav"case 20...29:fileName
= "diSound.wav"case 30...39:fileName
= "diSound.wav"case 40...49:fileName
= "diSound.wav"case 50...59:fileName
= "diSound.wav"default:fileName
= "diSound.wav"}return fileName
}}
extension ViewController {fileprivate
func createRecord() {var files
= LRSoundSourceManger.obtainFileName()if files
== nil {print("新建文件")files
= [String]()}let document
= NSSearchPathForDirectoriesInDomains(.documentDirectory
, .userDomainMask
, true).last! as NSString;let fileName
= recordFileName
.addingPercentEncoding(withAllowedCharacters
: .urlQueryAllowed
)let path
= document
.appendingPathComponent("\(fileName!).caf")let url
= URL(string
: path
)var recordSettings
= [String : Any]()recordSettings
[AVFormatIDKey] = kAudioFormatLinearPCMrecordSettings
[AVSampleRateKey] = 8000.0recordSettings
[AVNumberOfChannelsKey] = 1recordSettings
[AVLinearPCMBitDepthKey] = 16recorder
= try! AVAudioRecorder(url
: url
!, settings
: recordSettings
)recorder
.isMeteringEnabled
= truetry! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.record
)if recorder
.prepareToRecord() {print("準備錄音。。。")if self.recorder
.record() {print("開始錄音。。。")}}}fileprivate
func saveRecord() {print("錄音結束。。。")LRSoundSourceManger.saveFileName(recordFileName
)self.recorder
.stop()}
}
總結
以上是生活随笔為你收集整理的swift5 实现录音App的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。