Search code examples
c#audiodirectoryresxwmplib

How to extract file path from an audio file stored in project resource folder in C#


I am having a problem extracting the file directory of an audio file which is stored in my project resource folder. In my project, I have a mysounds.resx file in which I added a file (abc.mp3).

            WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
            wplayer.URL = "E:/xyz.mp3";
            wplayer.settings.setMode("loop",false);
            wplayer.controls.play();

Here, when I give the "E:/xyz.mp3" directory in wplayer.URL, it plays fine. But what I want to do is to get the file path from mysounds.resx file in which I stored abc.mp3 and I want to use files paths from mysounds.resx file, not any absolute paths.

Is there anyone who can help me? I am not very good in C#. I really need this work around. Thank you in advance.


Solution

  • Writing an audio file in a Resource to a temporary file, and then playing it using WMPLib.

    //Set up the temp path, I'm using a GUID for the file name to avoid any conflicts
    var temporaryFilePath = String.Format("{0}{1}{2}", System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N"), ".mp3") ;
    
    //Your resource accessor, my resource is called AudioFile
    using (var memoryStream = new MemoryStream(Properties.Resources.AudioFile))
    using(var tempFileStream = new FileStream(temporaryFilePath, FileMode.Create, FileAccess.Write))
    {
        //Set the memory stream position to 0
        memoryStream.Position = 0;
    
        //Reads the bytes from the audio file in resource, and writes them to the file
        memoryStream.WriteTo(tempFileStream);
    }
    
    //Play your file
    WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
    wplayer.URL = temporaryFilePath;
    wplayer.settings.setMode("loop", false);
    wplayer.controls.play();
    
    //Delete the file after use
    if(File.Exists(temporaryFilePath))
        File.Delete(temporaryFilePath);