如何在C#中播放参考资料中的.mp3文件?
我将music.mp3放在参考资料中,然后将Windows Media Player添加到参考资料中。我写了这段代码:如何在C#中播放参考资料中的.mp3文件?,c#,.net,resources,mp3,playback,C#,.net,Resources,Mp3,Playback,我将music.mp3放在参考资料中,然后将Windows Media Player添加到参考资料中。我写了这段代码: WindowsMediaPlayer wmp = new WindowsMediaPlayer(); wmp.URL = "music.mp3"; wmp.controls.play(); 它不起作用。如何从资源中播放.mp3文件?我做到了: WindowsMediaPlayer wmp = new WindowsMediaPl
WindowsMediaPlayer wmp = new WindowsMediaPlayer();
wmp.URL = "music.mp3";
wmp.controls.play();
它不起作用。如何从资源中播放.mp3文件?我做到了:
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");
}
我包装了mp3解码器库,并将其提供给.net开发人员。你可以在这里找到它: 包括将mp3文件转换为PCM和读取ID3标签的示例 读取您的资源,将其转换为PCM,并将其输出到waveOut类,该类作为interop.NET组件提供。不需要创建临时文件 sourceforge上还提供waveOut类: 或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();
创建这样的临时文件不应被视为有效的解决方案。无论好坏(我认为更糟),MediaPlayer.Play方法都不接受流作为输入。您最好使用exe部署MP3,并将文件位置传递给该函数。