要解决AVPlayer无法播放FFMPEG音频文件的问题,可以尝试将FFMPEG音频文件转换为AVPlayer支持的格式,例如MP3或AAC。以下是一个示例代码,演示如何使用AVAssetExportSession将FFMPEG音频文件转换为MP3格式:
import AVFoundation
func convertFFMPEGToMP3(inputURL: URL, outputURL: URL, completion: @escaping (Error?) -> Void) {
let asset = AVAsset(url: inputURL)
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
completion(nil)
return
}
exportSession.outputFileType = .mp3
exportSession.outputURL = outputURL
exportSession.exportAsynchronously {
if exportSession.status == .completed {
completion(nil)
} else {
completion(exportSession.error)
}
}
}
// 示例用法
let inputURL = URL(fileURLWithPath: "path_to_input_file")
let outputURL = URL(fileURLWithPath: "path_to_output_file.mp3")
convertFFMPEGToMP3(inputURL: inputURL, outputURL: outputURL) { error in
if let error = error {
print("转换失败:\(error.localizedDescription)")
} else {
print("转换成功!")
// 使用AVPlayer播放转换后的MP3文件
let playerItem = AVPlayerItem(url: outputURL)
let player = AVPlayer(playerItem: playerItem)
player.play()
}
}
请确保在使用代码示例时替换"path_to_input_file"和"path_to_output_file.mp3"为实际的文件路径。此示例假设您已经使用CocoaPods或Carthage等方法将AVFoundation库添加到项目中。