我正在开发一个播放音频文件的应用程序,并且可以在xcode模拟器(v10.2)中使该文件与AVPlayer实例一起播放,但是当尝试在我的设备上播放该文件时,音频文件无法播放。
我已阅读针对同一问题的回复并进行了检查:
以下是我设置录音机的代码:
func setUpRecorder(storyItem : StoryItem) {
// Generate unique ID for recording for the StoryItem
let uuid = UUID().uuidString + ".m4a"
let audioFileName = getDocumentDirectory().appendingPathComponent(uuid)
do {
try self.realm.write {
// storyItem.recording = audioFileName.absoluteString
storyItem.recording = uuid
}
} catch {
print("Error saving recording \(error)")
}
self.createStoryTableView.reloadData()
let recordSettings = [AVFormatIDKey : kAudioFormatAppleLossless,
AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,
AVEncoderBitRateKey : 320000,
AVNumberOfChannelsKey : 2,
AVSampleRateKey : 44100.0 ] as [String : Any]
do {
audioRecorder = try AVAudioRecorder(url: audioFileName, settings: recordSettings)
audioRecorder.delegate = self
audioRecorder.prepareToRecord()
} catch {
print(error)
}
}
播放音频文件的方法在这里:
func setUpPlayer(storyItem:StoryItem){
let audioFileName = getDocumentDirectory().appendingPathComponent(storyItem.recording)
getAudioDuration(audioFileName: audioFileName)
if storyItem.recording == "" {
let alert = UIAlertController(title: "There's no recording", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Cancel", style: .default) { (action) in
}
// This is what happens when cancel is pressed
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
} else {
player = AVPlayer(url: audioFileName)
player.volume = 1.0
}
}
如果有任何建议,我将不胜感激。可以使用唯一标识符(UUID)作为音频文件的名称吗?
答案 0 :(得分:1)
尝试在录制之前配置AVAudioSession共享实例。
赞:
// Configure AVAudioSession
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
assertionFailure("Failed to configure `AVAAudioSession`: \(error.localizedDescription)")
}