日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

swift5 实现录音App

發布時間:2023/12/18 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 swift5 实现录音App 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

swift5 實現錄音App


// // ViewController.swift // AudioRecoardDemo // // Created by lujun on 2022/1/25. //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())}// push到下一級頁面的時候結束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.isSelectedif 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()}}// MARK: - AudioServices 播放模式 extension ViewController {func playSound() {// 0,手機的靜音開關打開后,聽不到聲音let audioFilePath = Bundle.main.path(forResource: fileName(), ofType: nil)let url = URL(fileURLWithPath: audioFilePath!)// 1.獲取系統聲音IDvar soundID: SystemSoundID = 0AudioServicesCreateSystemSoundID(url as CFURL, &soundID)// 2.播放音頻AudioServicesPlaySystemSound(soundID)AudioServicesPlaySystemSoundWithCompletion(soundID) {print("AudioServices - 播放結束---")DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5, execute: {print("AudioServices - 播放開始---")self.playSound()})}} }// MARK: - AVFoundation 播放模式 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()}} } // MARK: - 獲取文件的名字 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] = kAudioFormatLinearPCM// 采樣率recordSettings[AVSampleRateKey] = 8000.0// 通道數recordSettings[AVNumberOfChannelsKey] = 1// 采樣的位數recordSettings[AVLinearPCMBitDepthKey] = 16// 音頻質量,采樣質量// 這個設置完成后就會:prepareToRecord:準備失敗;record:開始錄音失敗recorder = try! AVAudioRecorder(url: url!, settings: recordSettings)recorder.isMeteringEnabled = true// 這個設置不加的話,record方法返回falsetry! 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。