iosswiftavfoundationavplayeravasset

Swift -check if url asset has sound


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

Solution

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