Search code examples
c#videouwpwindows-media-player

Cannot open mp4's made from MediaCapture in C# UWP app


I am writing a UWP app in C# that uses the camera to take a video.

My test app is simple: start recording, wait five seconds, then stop recording. It will save the recording as an mp4.

However, after I ran this app, I was not able to play the mp4 with the Windows 10 app Movies & TV. When I double-clicked the file, nothing would happen. I cannot even open Movies & TV; when I double-click that from the Start menu, nothing happens either.

However, I was able to "Open with..." the mp4's with Windows Media Player, a non-Windows store app. After reading this question and how if you do not properly clean up the MediaCapture object in your code, other apps may hang; my theory is that I did not clean up the MediaCapture properly; the Windows store app Movies & TV suffered as a result, but the non-Windows store app Windows Media Player could still play the videos.

Here are the important parts of the code:

WebCam class:

    public async void InitVideo()
    {
        mediaCapture = new MediaCapture();
        await mediaCapture.InitializeAsync();
    }

    public async void RecordVideo(string fileName)
    {
        recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);

        MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto);

        await mediaCapture.StartRecordToStorageFileAsync(recordProfile, recordStorageFile);

        recording = true;
    }

    public async Task StopVideo()
    {
        await mediaCapture.StopRecordAsync();

        recording = false;
    }

    public void Reset()
    {
        mediaCapture.Dispose();
        mediaCapture = null;
    }

In MainPage.xaml, there is a single button on the screen named startRecording. This is what happens when that button is clicked:

        WebCam camera = new WebCam();

        camera.InitVideo();
        camera.RecordVideo("file.mp4");

        await Task.Delay(TimeSpan.FromSeconds(5));

        await camera.StopVideo();

        camera.Reset();

Is my theory correct or is it something else?


Solution

  • You've done everything correctly here from a basic video capture point of view. If you're finding that the video is opening fine in Windows Media Player but not the Windows Film/TV app, it could be an issue with those apps.

    I've attached a helper class that I use in my own camera apps that you might be able to grab some bits of here: CameraCapture.cs - WindowsAppCodeSnippets (GitHub)