Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created June 27, 2016 19:04
Show Gist options
  • Select an option

  • Save primaryobjects/a64fd1c387e537589b1c1b153752e3e0 to your computer and use it in GitHub Desktop.

Select an option

Save primaryobjects/a64fd1c387e537589b1c1b153752e3e0 to your computer and use it in GitHub Desktop.

Revisions

  1. primaryobjects created this gist Jun 27, 2016.
    6 changes: 6 additions & 0 deletions App.config
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <appSettings>
    <add key="ffmpeg:ExeLocation" value="../../../tools/ffmpeg.exe" />
    </appSettings>
    </configuration>
    56 changes: 56 additions & 0 deletions mp4towav
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    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;
    }