Skip to content

Instantly share code, notes, and snippets.

@skittleson
Created July 6, 2023 16:55
Show Gist options
  • Save skittleson/64a0cb46c5ade061d9ea01a6c76a2644 to your computer and use it in GitHub Desktop.
Save skittleson/64a0cb46c5ade061d9ea01a6c76a2644 to your computer and use it in GitHub Desktop.
Record ffmpeg
public static async Task RecordAsync(Stream stream, string microphone, CancellationToken cancellationToken, Action<double> detectedSilenceCallback = null)
{
// do this to get audio device with a mic
// ffmpeg -list_devices true -f dshow -i dummy
// pick one then add it to the audio device
// ffmpeg -f dshow -i audio="Microphone (HD Pro Webcam C920)" -ar 16000 output.wav
using var gracefulCts = new CancellationTokenSource();
try
{
// ffmpeg -f dshow -i audio="Microphone Array (Intel® Smart Sound Technology for Digital Microphones)" -ar 16000 -preset ultrafast -tune zerolatency -b 900k -f mpegts udp://127.0.0.1:9876
var silenceEnded = 0.0;
var cmd = Cli.Wrap("ffmpeg")
.WithArguments(new string[] {
"-f dshow",
$"-i audio=\"{microphone}\"",
"-ar 16000",
//"-af silencedetect=d=1.5",
"-af \"silencedetect=n=-30dB:d=2\"",
"-nostats",
"-f mpegts",
"pipe:1"
}, false) |
(PipeTarget.ToStream(stream),
PipeTarget.ToDelegate(buffer =>
{
Console.WriteLine(buffer);
if (buffer.Contains("silencedetect")
&& detectedSilenceCallback != null)
{
//silence_end is the start of a request
//silence_start is when audio should be processed
// the difference in time should be greater than 5 seconds at least
if (buffer.Contains("silence_duration"))
silenceEnded = Convert.ToDouble(buffer.Split("silence_end:")[1].Split("|")[0].Trim());
else if (buffer.Contains("silence_start")) {
var silenceStart = Convert.ToDouble(buffer.Split("silence_start:")[1].Trim());
detectedSilenceCallback?.Invoke(silenceStart - silenceEnded);
}
}
})
);
await cmd.ExecuteAsync(cancellationToken, gracefulCts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("timeout");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment