Skip to content

Instantly share code, notes, and snippets.

@gregorypilar
Forked from primaryobjects/App.config
Created September 11, 2018 14:21
Show Gist options
  • Save gregorypilar/712295d0a857b5faa1dfbeee54bf306e to your computer and use it in GitHub Desktop.
Save gregorypilar/712295d0a857b5faa1dfbeee54bf306e to your computer and use it in GitHub Desktop.
Example C# code to extract audio from YouTube and save as trimmed 15-second WAV file. Requires ffmpeg.exe
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ffmpeg:ExeLocation" value="../../../tools/ffmpeg.exe" />
</appSettings>
</configuration>
using YoutubeExtractor;
using Frapper;
private static void Main()
{
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls("https://www.youtube.com/watch?v=GRubo5wg6_Y", false);
string path = DownloadAudioQuick(videoInfos);
path = Mp4ToWav(path, 15);
}
private static string RemoveIllegalPathCharacters(string path)
{
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
return r.Replace(path, "");
}
private static string DownloadAudioQuick(IEnumerable<VideoInfo> videoInfos)
{
VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 0);
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), RemoveIllegalPathCharacters(video.Title) + ".mp4");
var audioDownloader = new VideoDownloader(video, path);
audioDownloader.Execute();
return path;
}
private static string Mp4ToWav(string path, int seconds = 10)
{
string result;
return Mp4ToWav(path, seconds, out result);
}
private static string Mp4ToWav(string path, int seconds, out string result)
{
FFMPEG ffmpeg = new FFMPEG();
// Trim mp4.
string outputPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_trim.mp4";
string result1 = ffmpeg.RunCommand("-ss 00:00:00.0 -t 00:00:" + seconds.ToString().PadLeft(2, '0') + ".0 -i \"" + path + "\" -c copy \"" + outputPath + "\"");
// Convert to wav.
string wavPath = outputPath.Replace(".mp4", ".wav");
string result2 = ffmpeg.RunCommand("-i \"" + outputPath + "\" -acodec pcm_u8 -ar 22050 \"" + wavPath + "\"");
result = result1 + "\n\n\n" + result2;
// Cleanup.
File.Delete(path);
File.Delete(outputPath);
return wavPath;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment