Search code examples
c#ffmpegmedia-playerwebmm4a

C# Play MPEG audio files


I'm looking for a way to play mpeg audio files in C#. With mp3 the case is simple:

    System.Windows.Media.MediaPlayer player = new System.Windows.Media.MediaPlayer();
    player.Open(new System.Uri(File));
    player.Play();

I'm looking for a way to play with similar simplicity the m4a or webm audio files. For now I'm desperate and I'm trying to make a workaround:

        String path = Path.GetFullPath("./x.m4a");
        Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "ffplay.exe";
        startInfo.Arguments = "-vn -showmode 0 " + path;
        process.StartInfo = startInfo;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo.CreateNoWindow = true;
        process.Start();

For now I am able to play x.m4a file, but it doesn't stop when I exit the file. Also I'm afraid I won't have much control over the track flow. Is there any different method (with NuGet package for example) to play mpeg files?


Solution

  • Ok, I found a way. Apparently the NAudio library does the job, but you need to install codecs for MPEG4 layer. After this it's pretty simple:

    NAudio.Wave.WaveOut wave = new NAudio.Wave.WaveOut();
    wave.Init(fileName);
    wave.Play();
    

    EDIT: Ironically, month later I found my own answer to same problem. For older versions of NAudio (for example for .NET 4.0) you need a little workaround:

            var wave = new WaveOut();
            var x = new AudioFileReader(filename);
            wave.Init(x);
            wave.Play();
    
            while(true)System.Threading.Thread.Sleep(100);
    

    Last loop is added simply because system needs to wait until player finishes. Feel free to edit that out.