How to play .mp3 file from resources in C#?

守給你的承諾、 提交于 2020-01-12 02:26:47

问题


I put music.mp3 in resources and then I added Windows Media Player to references. I wrote this code:

WindowsMediaPlayer wmp = new WindowsMediaPlayer();
            wmp.URL = "music.mp3";
            wmp.controls.play();

It doesn't work. How can I play .mp3 file from resources?


回答1:


I did it:

WindowsMediaPlayer wmp = new WindowsMediaPlayer();
        Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PostGen.Resources.Kalimba.mp3");
        using (Stream output = new FileStream ("C:\\temp.mp3", FileMode.Create))
        {
            byte[] buffer = new byte[32*1024];
            int read;

            while ( (read= stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }
        wmp.URL = "C:\\temp.mp3";
        wmp.controls.play();

We have to delete this temporary file:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        File.Delete("C:\\temp.mp3");
    }



回答2:


I wrapped mp3 decoder library and made it available for .net developers. You can find it here:

http://sourceforge.net/projects/mpg123net/

Included are the samples to convert mp3 file to PCM, and read ID3 tags.

Read your resource, convert it to PCM and output it to waveOut class that is available as interop .NET component. No need to create temp files.

waveOut classes available also on sourceforge:

http://windowsmedianet.sourceforge.net/




回答3:


Or Tyr this;

        var file = $"{Path.GetTempPath()}temp.mp3";
            if (!File.Exists(file))
            {
                using (Stream output = new FileStream(file, FileMode.Create))
                {
                    output.Write(Properties.Resources.Kalimba, 0, Properties.Resources.Kalimba.Length);
                }
            }
            var wmp = new WindowsMediaPlayer { URL = file };
            wmp.controls.play();


来源:https://stackoverflow.com/questions/3337110/how-to-play-mp3-file-from-resources-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!