• Stars
    star
    133
  • Rank 272,600 (Top 6 %)
  • Language
    C#
  • License
    MIT License
  • Created about 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

FFmpeg on Web Assembly

FFmpegBlazor

NuGet Badge License: MIT

FFmpegBlazor provides ability to utilize ffmpeg.wasm from Blazor Wasm C#.
ffmpeg.wasm is a pure Webassembly / Javascript port of FFmpeg. It enables video & audio record, convert and stream right inside browsers.
Supports Lazy loading of ffmpeg binary. It is self hosted version one time download of core ffmpeg wasm lib will be 25Mb.

Video Tutorial : Link Credit Dev Express

Roadmap for .NET 8

  • Exploring to reduce extra configuration steps aka no longer need to add Wasm headers to run app locally.
  • Robust integration with .NET 8 wasm threads and possibilty to use newer JSInterop API.

Installation

Download package via Nuget or DotNet CLI and you are good to go , no extra configuration required.

dotnet add package FFmpegBlazor 

API Documentation

Running WASM App

Currently we need to use a workaround to run FFmpegApps on web assembly, this will be removed in .NET 7 (Early September 2022) once Multi threading support is available on WASM.

We need to add 2 headers in Blazor WASM-local-server and in actual deployment static server also

Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin

To do so we can create a web.config file in root of our project with content

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<system.webServer>
		<httpProtocol>
			<customHeaders>
				<add name="Cross-Origin-Embedder-Policy" value="require-corp"/>
				<add name="Cross-Origin-Opener-Policy" value="same-origin"/>
			</customHeaders>
		</httpProtocol>
	</system.webServer>

</configuration>

Use IIS Express to run apps locally. Also In actual deployment we need to add these 2 headers in server config to avoid SharedArrayBuffer not defined error. You can check Netlify deployment sample here.
Thanks to @aokocax for helping with it.

Sample

Here is a sample page to convert mp4 to mp3 and play it in browser.

@page "/"
@using FFmpegBlazor
@inject IJSRuntime Runtime
@using Microsoft.AspNetCore.Components.Forms


<InputFile OnChange="fileLoad" /><br /> <br />
<video width="300" height="200" autoplay controls src="@url" /><br /><br />
<button class="btn btn-primary" @onclick="Process">Convert Mp3</button><br /><br />
<audio controls src="@url2" />

@code
{
    string url; string url2;
    FFMPEG ff;
    byte[] buffer;

    protected override async Task OnInitializedAsync()
    {
        if (FFmpegFactory.Runtime == null)
        {
            FFmpegFactory.Logger += WriteLogs;
            FFmpegFactory.Progress += ProgressChange;
        }

        //initialize Library
        await FFmpegFactory.Init(Runtime);
    }

    async void fileLoad(InputFileChangeEventArgs v)
    {
        //get fist file from input selection
        var file = v.GetMultipleFiles()[0];

        //read all bytes
        using var stream = file.OpenReadStream(100000000); //Max size for file that can be read
        buffer = new byte[file.Size];

        //read all bytes
        await stream.ReadAsync(buffer);

        //create a video link from buffer so that video can be played
        url = FFmpegFactory.CreateURLFromBuffer(buffer, "myFile.mp4", file.ContentType);

        //reRender DOM
        StateHasChanged();
    }

    async void Process()
    {
        //create an instance
        ff = FFmpegFactory.CreateFFmpeg(new FFmpegConfig() { Log = true });

        //download all dependencies from cdn
        await ff.Load(); 

        if (!ff.IsLoaded) return;

        //write buffer to in-memory files (special emscripten files, Ffmpeg only interact with this file)
        ff.WriteFile("myFile.mp4", buffer);

        //Pass CLI argument here equivalent to ffmpeg -i myFile.mp4 output.mp3
        await ff.Run("-i", "myFile.mp4", "output.mp3");

        //delete in-memory file
        //ff.UnlinkFile("myFile.mp4");
    }

    async void ProgressChange(Progress m)
    {
         // display progress % (0-1)
        Console.WriteLine($"Progress {m.Ratio}");

        //if ffmpeg processing is complete (generate a media URL so that it can be played or alternatively download that file)
        if (m.Ratio == 1)
        {
            //get bytepointer from c wasm to c#
            var res = await ff.ReadFile("output.mp3");


            //generate a url from file bufferPointer
            url2 = FFmpegFactory.CreateURLFromBuffer(res, "output.mp3", "audio/mp3");

            //Download the file instantly

            //FFmpegFactory.DownloadBufferAsFile(res, "output.mp3", "audio/mp3");

            StateHasChanged();
        }
    }

    void WriteLogs(Logs m)
    {
        Console.WriteLine(m.Type + " " + m.Message);
    }
}

More Repositories

1

BlazorML5

ML5 Machine Learning For Blazor with JSInterop mechanism
C#
54
star
2

VisualScriptingSystem

Visual Scripting System Implementation
C++
20
star
3

FileShareLib

TCP File Transfer libary using c#
C#
17
star
4

BlazorBindGen

C#
16
star
5

Streamer-Desktop

A application build with electron.js that can broadcast local multimedia content to other nearby devices directly with wifi.
JavaScript
16
star
6

Sonic-Downloader

Fast Download Manager
C#
13
star
7

DrawToMesh

C#
12
star
8

HTTP-Server

C# Http Server
C#
9
star
9

DotNetTable

Beautiful Console Tables
C#
8
star
10

8085-Simulator

A web based Simulator for Microprocessors
JavaScript
8
star
11

Tik-Tac-Toe

Advanced Unbeatable AI Tik Tac Toe
C#
8
star
12

Genetic-AI

AI learns to get to the ball .
C#
7
star
13

OnFire

Quick lIbrary for Firebase Email Auth and Database
C#
7
star
14

GeoQuery

GeoHash Algorithm implemetation
C#
7
star
15

File-Cryptographer

C#
7
star
16

Blazor.Drawable

SVG based Renderer for Razor C#
C#
7
star
17

MinLang

A statically typed turing complete minimal programming language
Rust
7
star
18

CricketInfo

Retrieve Data About ongoing Cricket Match C#
C#
6
star
19

CacheGen

C#
6
star
20

SplineSystem-Unity

C#
6
star
21

ai.play.io

Similar to Teachable Machine,train image classes on Client side (WEBGL)
HTML
6
star
22

AMP

Convolutional Neural Net
HTML
5
star
23

Blaze.JS

Jsdoc Parser
C#
5
star
24

Dino-Cheat

Since Chrome Dino game is subject to change you need to modify the points in Rig for your matching configuration in ImageProcessing.cs file
C#
5
star
25

MxML-Parser

JavaScript
5
star
26

KNN

C#
5
star
27

DiscriminatedUnion

C#
5
star
28

NeuralNetwork

My own Implementation for ML Algorithm.
C#
5
star
29

UMID

HackCBSv2
C#
5
star
30

Noise-Crafter

C#
4
star
31

ffmpegBlazor-Deployed

Demonstration of Netlify deployment
JavaScript
4
star
32

Parsers

C#
4
star
33

WBoostServer

Spatial Geo Indexing with CosmoDB
C#
4
star
34

AutoIndexer

C#
3
star
35

LibSaavn

C#
3
star
36

SourceGenExample

C#
3
star
37

sps014

2
star
38

Blender-STL-importer

C++
2
star
39

Localizer

C#
2
star
40

uwpTestMica

C#
1
star
41

FPSController

Unity Basic FPS Controller
C#
1
star