在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开发中需要获取录音和播放音频的权限,可以在Info.plist文件中添加对应的权限描述。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。