Swift -check if url asset has sound

我与影子孤独终老i 提交于 2020-12-15 07:17:10

问题


My screen cracked and my phone has no sound capabilities. I recorded a video using the camera. When I select the video url from didFinishPickingMediaWithInfo I tried to check if the video has sound or not but player.currentItem?.asset.tracks says the video does have sound (the device and recorded video definitely has no sound).

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) ***       
       }   
   }
}

回答1:


This is the way to do it:

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")
}


来源:https://stackoverflow.com/questions/64733573/swift-check-if-url-asset-has-sound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!