Skip to content

Instantly share code, notes, and snippets.

@skittleson
Last active April 26, 2023 19:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skittleson/095c0e9a4d56fbc53b80d22029e90c9b to your computer and use it in GitHub Desktop.
Save skittleson/095c0e9a4d56fbc53b80d22029e90c9b to your computer and use it in GitHub Desktop.
Cross platform audio player in dotnet
// I've used a lot of libs including the popular ones for dotnet such as NAudio but all seem to be overly complicated or not cross platform.
// 1. install ffplay on your platform. for Windows `choco install ffplay`. Debian `apt install ffmpeg`.
// 2. install nuget pkg `CliWrap`
// 3. send your audio stream to the method.
public static async Task PlayAsync(Stream stream, CancellationToken cancellationToken)
{
var result = await Cli.Wrap("ffplay")
.WithStandardInputPipe(PipeSource.FromStream(stream))
.WithArguments($"-autoexit -nodisp -hide_banner -loglevel error -fs -")
.ExecuteAsync();
}
@spencerkittleson
Copy link

spencerkittleson commented Apr 26, 2023

import subprocess
import psutil
import os
import signal
from threading import Thread

@staticmethod
def play(stream: bytes) -> None:
    """play wav stream using ffplay"""
    for proc in psutil.process_iter():
        if "ffplay" in proc.name():
            print(f"kill process {proc.pid}")
            os.kill(proc.pid, signal.SIGTERM)
            break
    command = "ffplay -autoexit -nodisp -hide_banner -loglevel error -fs -".split(
        ' ')

    def run(c, s): return subprocess.run(c, input=s, shell=True)
    (Thread(target=run, args=(command, stream))).start()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment