AVPlayer可以使用.m4a的文件扩展名工作,但不能使用.aac扩展名,使用AVAssetExportSession时也是如此。下面是一种解决方法的代码示例:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
// 播放.m4a文件
guard let m4aFilePath = Bundle.main.path(forResource: "audio", ofType: "m4a") else {
return
}
let m4aFileURL = URL(fileURLWithPath: m4aFilePath)
let m4aAsset = AVAsset(url: m4aFileURL)
let m4aPlayerItem = AVPlayerItem(asset: m4aAsset)
player = AVPlayer(playerItem: m4aPlayerItem)
player?.play()
// 将.aac文件转换为.m4a文件
guard let aacFilePath = Bundle.main.path(forResource: "audio", ofType: "aac") else {
return
}
let aacFileURL = URL(fileURLWithPath: aacFilePath)
let aacAsset = AVAsset(url: aacFileURL)
let exportSession = AVAssetExportSession(asset: aacAsset, presetName: AVAssetExportPresetAppleM4A)
exportSession?.outputFileType = .m4a
guard let m4aOutputFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("output.m4a") else {
return
}
exportSession?.outputURL = m4aOutputFilePath
exportSession?.exportAsynchronously(completionHandler: {
if exportSession?.status == .completed {
// 转换成功,可以使用AVPlayer播放.m4a文件
let m4aAsset = AVAsset(url: m4aOutputFilePath)
let m4aPlayerItem = AVPlayerItem(asset: m4aAsset)
DispatchQueue.main.async {
self.player = AVPlayer(playerItem: m4aPlayerItem)
self.player?.play()
}
} else {
// 转换失败
print("转换失败:\(exportSession?.error?.localizedDescription ?? "")")
}
})
}
}
上述代码首先使用AVPlayer播放名为"audio.m4a"的文件。然后,它将名为"audio.aac"的文件转换为.m4a格式,并将输出文件保存在应用程序的文档目录中。转换完成后,它使用AVPlayer播放转换后的.m4a文件。
请注意,上述代码中的文件名和路径是示例,你需要根据你的实际文件名和路径进行调整。