//
// Fast.swift
// FastSwiftKit
//
// Created by XX on 2023/9/7.
//
import AVFoundation
public class FastAudioManager {
public static let shared = FastAudioManager()
// MARK: 音频录制
private var audioRecorder: AVAudioRecorder?
private var audioSession: AVAudioSession = AVAudioSession.sharedInstance()
private var maxtime: Int?
var audioFilesURL:URL?
/// 开始录音
/// - Returns: URL
public func startRecording(_ serverHost:String?,_ quality:String?,_ maxtime:Int?) -> URL?{
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playAndRecord, mode: .default, options: [])
try audioSession.setActive(true, options: [])
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: Int(quality ?? "0"),
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
let time = Date().timeIntervalSince1970
audioFilesURL = documentDirectory.appendingPathComponent("\(Int(time)).m4a")
audioRecorder = try AVAudioRecorder(url: audioFilesURL!, settings: settings)
audioRecorder?.record()
self.maxtime = maxtime
Timer.scheduledTimer(withTimeInterval: 0, repeats: true) {[weak self] t in
if Int(self?.audioRecorder?.currentTime ?? 0.0) >= Int(maxtime ?? 0){
print("录音时间到期")
self?.audioRecorder?.stop()
self?.audioRecorder = nil
t.invalidate()
}
}
return audioFilesURL
} catch {
print("Failed to start recording")
return nil
}
}
public func getAudioRecorderCurrentTime() -> TimeInterval? {
return audioRecorder?.currentTime
}
/// 停止录音
public func stopRecording() {
audioRecorder?.stop()
audioRecorder = nil
}
// MARK: 播放音频
var audioPlayer: AVAudioPlayer?
/// 播放音频
/// - Parameter audioURL: URL
public func playAudio(audioURL: URL) {
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
try AVAudioSession.sharedInstance().setActive(true, options: [])
if ((audioPlayer?.isPlaying) != nil) == true{
audioPlayer?.stop()
}
audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
audioPlayer?.play()
} catch {
print("Failed to play audio file")
}
}
/// 暂停
public func pauseAudio() {
audioPlayer?.pause()
}
/// 恢复
public func resumeAudio() {
audioPlayer?.play()
}
//
public func getCurrentTime() -> TimeInterval? {
return audioPlayer?.currentTime
}
public func getDuration() -> TimeInterval? {
return audioPlayer?.duration
}
}
extension FastAudioManager {
/// 下载音频并播放 、、、、、、、
/// - Parameter url: url网络地址
func downloadAndPlay(form url:String){
// 下载音频
// FastNetWorking().download(url) { [weak self] fileUrl in
// self?.playAudio(audioURL: fileUrl)
// } fai: { str in
//
// }
}
func recordAndUplaod(to url:String){
// if let fileUrl = self.startRecording(100){
// // 上传音频
// FastNetWorking().upload(url, fileUrl, nil) { str in
//
// } fai: { fai in
//
// }
// }
}
}
标签:audioRecorder,功能,Int,audioPlayer,录音,self,func,iosSDK,public From: https://www.cnblogs.com/supersr/p/18586299