简体   繁体   English

如何从C#中的资源中播放.mp3文件?

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

I put music.mp3 in resources and then I added Windows Media Player to references. 我把music.mp3放在资源中,然后我将Windows Media Player添加到引用中。 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? 如何从资源中播放.mp3文件?

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");
    }

I wrapped mp3 decoder library and made it available for .net developers. 我包装了mp3解码器库,并为.net开发人员提供了它。 You can find it here: 你可以在这里找到它:

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

Included are the samples to convert mp3 file to PCM, and read ID3 tags. 包括将mp3文件转换为PCM的示例,以及读取ID3标签。

Read your resource, convert it to PCM and output it to waveOut class that is available as interop .NET component. 读取您的资源,将其转换为PCM并将其输出到waveOut类,该类可用作interop .NET组件。 No need to create temp files. 无需创建临时文件。

waveOut classes available also on sourceforge: sourceforge上也提供了waveOut类:

http://windowsmedianet.sourceforge.net/ http://windowsmedianet.sourceforge.net/

Or Tyr this; 或者Tyr这个;

        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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM