Swift - 检查 url 资产是否有声音
Swift -check if url asset has sound
我的屏幕裂了,我的 phone 没有声音功能。我用相机录制了一段视频。当我 select 来自 didFinishPickingMediaWithInfo
的视频 url 我试图检查视频是否有声音但 player.currentItem?.asset.tracks
说视频确实有声音(设备和录制的视频肯定没有声音)。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// ...
guard let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL else { return }
// ...
let asset = AVURLAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
if let tracks = player.currentItem?.asset.tracks {
switch tracks.count {
case 0:
print("tracks -0: audio only")
case 1:
print("tracks -1: video only ")
case 2:
print("tracks -2: audio and video") // this prints when the video does have sound (recorded before the screen cracked)
default:
print("tracks -default: audio and video") // *** this always prints when the video doesn't have sound (recorded after the screen cracked) ***
}
}
}
方法是这样的:
let asset = AVURLAsset(url: url)
// if using a mixComposition it's: let asset = mixComposition (an AVMutableComposition itself is an asset)
let audioTrack = asset.tracks(withMediaType: .audio)
if audioTrack.isEmpty {
print("this video has no sound")
} else {
print("this video has sound")
}
我的屏幕裂了,我的 phone 没有声音功能。我用相机录制了一段视频。当我 select 来自 didFinishPickingMediaWithInfo
的视频 url 我试图检查视频是否有声音但 player.currentItem?.asset.tracks
说视频确实有声音(设备和录制的视频肯定没有声音)。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// ...
guard let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL else { return }
// ...
let asset = AVURLAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
if let tracks = player.currentItem?.asset.tracks {
switch tracks.count {
case 0:
print("tracks -0: audio only")
case 1:
print("tracks -1: video only ")
case 2:
print("tracks -2: audio and video") // this prints when the video does have sound (recorded before the screen cracked)
default:
print("tracks -default: audio and video") // *** this always prints when the video doesn't have sound (recorded after the screen cracked) ***
}
}
}
方法是这样的:
let asset = AVURLAsset(url: url)
// if using a mixComposition it's: let asset = mixComposition (an AVMutableComposition itself is an asset)
let audioTrack = asset.tracks(withMediaType: .audio)
if audioTrack.isEmpty {
print("this video has no sound")
} else {
print("this video has sound")
}