在我的应用程序中,用户可以录制音频,最长可达25秒。
我将文档目录中的音频保存为“1.m4a”,每当用户再次录制时,它将替换“1.m4a”中的原始文件。
我想播放“1.m4a”作为本地通知的声音。我发现有消息称这是不可能的,但也有一些消息来源称它可能存储在Library / Sounds目录中。这是什么意思?任何人都可以教我如何做到这一点!
我录制音频的功能很好用,我有一个按钮,可以在点击时播放录制的音频。
录制音频:
@IBAction func recordAction(_ sender: UIButton) {
counter = 0
startCounter()
if (audioRecorder == nil) {
audioReadyLabel.isHidden = true
counterLabelOutlet.isHidden = false
numberOfRecords = 1
let fileName = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
do {
audioRecorder = try AVAudioRecorder(url: fileName, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
stopOutlet.isHidden = false
stopLabelOutlet.isHidden = false
recordOutlet.isHidden = true
recordLabelOutlet.isHidden = true
}
catch {
displayAlert(title: "Oops", message: "Recording failed")
}
}
else {
stopOutlet.isHidden = true
stopLabelOutlet.isHidden = true
audioRecorder.stop()
//what does the below mean ***
audioRecorder = nil
counterTimer.invalidate()
}
}
播放音频:
func playPeptalk() {
let path = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
do {
audioPlayer = try AVAudioPlayer(contentsOf: path)
audioPlayer.play()
}
catch {
}
}
本地通知:
let content = UNMutableNotificationContent()
content.title = "Rise & Shine"
content.subtitle = "Let's start the day!"
content.sound = UNNotificationSound(named: UNNotificationSoundName("1.m4a"))
来自Docs
音频文件必须已经在用户的设备上才能播放。如果您为通知使用预定义的声音集,请将音频文件包含在应用程序包中。对于所有其他声音,请将音频文件的副本放在应用程序容器目录的Library / Sounds文件夹中。 UNNotificationSound对象仅在这两个位置中查找