中间鸽了两天,产品又给了新的需求,获取本地音乐并添加到视频中去。08的时候已经获取到本地音乐了,但是发现本地音乐的assetURL路径添加到视频的时候出现问题,需要把它转为本地路径。网上查到AVAssetExportSessionexport方法,由于是OC的,这里把它转为swift.
代码如下:
let everything = MPMediaQuery()
let itemsFromGenericQuery = everything.items
for song in itemsFromGenericQuery! {
let songTitle = song.value(forProperty: MPMediaItemPropertyTitle) as! String
let url = song.value(forProperty: MPMediaItemPropertyAssetURL)
let songAsset = AVURLAsset.init(url: url as! URL)
let fileManager = FileManager.default
let dirs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectoryPath = dirs.first
let exporter = AVAssetExportSession.init(asset: songAsset, presetName: AVAssetExportPresetAppleM4A)
exporter?.outputFileType = "com.apple.m4a-audio"
let exportFile = documentsDirectoryPath?.appending(songTitle + ".m4a")
if fileManager.fileExists(atPath: exportFile!) {
try? fileManager.removeItem(at: URL.init(string: exportFile!)!)
}
let exportURL = URL.init(fileURLWithPath: exportFile!)
exporter?.outputURL = exportURL
exporter?.exportAsynchronously(completionHandler: {
print(exporter!.status)
}
print(path!)
print(exportURL)
}
最后可以查看本地音乐的assetURL和本地路径