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

7
我把music.mp3放在资源文件夹中,然后将Windows Media Player添加到引用中。我编写了以下代码:

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

它不能正常工作。我该如何从资源中播放.mp3文件?

3个回答

4
我做到了:
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();

我们需要删除这个临时文件:

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

创建这样的临时文件不应被视为有效的解决方案。MediaPlayer.Play方法,无论好坏(我会说更糟),都不接受流作为输入。最好将MP3与您的exe一起部署并将文件位置传递给该函数。 - Seanba

2
我封装了mp3解码库,并使其可供.net开发人员使用。你可以在这里找到它:

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

包括将mp3文件转换为PCM和读取ID3标签的示例。
读取您的资源,将其转换为PCM并输出到waveOut类,该类作为interop .NET组件可用。无需创建临时文件。
waveOut类也可在sourceforge上获得。

http://windowsmedianet.sourceforge.net/


-1

或者尝试这个;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接