您好,登錄后才能下訂單哦!
在UIKit中,可以使用AVFoundation框架來實現音頻錄制和播放功能。下面是一個簡單的示例代碼來演示如何實現音頻錄制和播放功能:
import AVFoundation
var audioRecorder: AVAudioRecorder?
var audioPlayer: AVAudioPlayer?
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
func startRecording() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playAndRecord, mode: .default)
try audioSession.setActive(true)
let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder?.record()
} catch {
print("Recording failed")
}
}
func stopRecording() {
audioRecorder?.stop()
audioRecorder = nil
}
func playRecordedAudio() {
let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
do {
audioPlayer = try AVAudioPlayer(contentsOf: audioFilename)
audioPlayer?.play()
} catch {
print("Playback failed")
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
這樣就可以實現簡單的音頻錄制和播放功能。需要注意的是,在iOS開發(fā)中需要獲取錄音和播放音頻的權限,可以在Info.plist文件中添加對應的權限描述。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。