Detect if video has audio track (from URL)

I’m loading different videos from URL and play them in the Unity VideoPlayer component. Is there any way to detect whether the video has an audio track (or multiple) or not?

Use case: would like to show audio icon to user only if the video has audio.

I tried .audioTrackCount and .controlledAudioTrackCount. audioTrackCount always returns 0, controlledAudioTrackCount always returns 1. I wait till isPrepared = true before I check the counts.

Also if I check the VideoPlayer component in the Inspector Controlled Tracks shows 1 - even for videos without any audio tracks.

What you’re suggesting there seem the be the good… Could you share some of your code? Thanks!

sure, thanks for your reply. here is the basic code I’m using:

public async UniTask<bool> LoadVideo(VideoPlayer videoPlayer, string url)
    {
        bool prepareSuccess = await PrepareVideo(videoPlayer, url, aRExample);
        if (!prepareSuccess || videoPlayer == null || videoPlayer.gameObject == null)
            {
                return false;
            }
        videoPlayer.gameObject.SetActive(true);

        // this is not working, controlledAudioTrackCount always 1, audioTrackCount always 0
        if (videoPlayer.controlledAudioTrackCount > 0 )
        {
            Debug.Log("should show audio hint for video!");
        }

    }

private async UniTask<bool> PrepareVideo(VideoPlayer videoPlayer, string url)
    {
        try
        {
            // Wait until video is prepared
            videoPlayer.url = url;
            videoPlayer.gameObject.transform.localScale = new Vector3(0f, 0f, 0f);
            videoPlayer.gameObject.SetActive(true);
            videoPlayer.errorReceived += VideoPlayer_errorReceived;
            videoPlayer.Prepare();
            _cancellationTokenSource = new CancellationTokenSource();
            await UniTask.WaitUntil((() => videoPlayer == null || videoPlayer.isPrepared),
                cancellationToken: _cancellationTokenSource.Token);
            videoPlayer.aspectRatio = VideoAspectRatio.FitHorizontally;
            return true;
        }
        catch (Exception e)
        {
            Debug.Log("catch error: " + e);
            if (videoPlayer != null && videoPlayer.gameObject != null)
            {
                videoPlayer.gameObject.SetActive(false);
            }
            return false;
        }
    }

I’m generally more the audio guy, but I gather that sometimes metadata is not completely available just after Prepare(). You might have to start the video for everything to be set right. Do you still get this if you hook your check to the videoPlayer.started callback?

@The_Island any thought?

Perfect, in the videoPlayer.started callback it works if I check for videoPlayer.audioTrackCount. Thank you very much for your help!

1 Like