使用另一个简单的办法是:
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
string mp3FileName = "music.mp3";
myplayer.URL = AppDomain.CurrentDomain.BaseDirectory + mp3FileName;
myplayer.controls.play();
这将播放从您的可执行文件位于该目录中的MP3同样重要的是要注意,不需要思考,这会增加不必要的性能成本。
作为后续约嵌入MP3作为一种资源的评论,下面的代码可以实现,一旦它被添加:
Assembly assembly = Assembly.GetExecutingAssembly();
string tmpMP3 = AppDomain.CurrentDomain.BaseDirectory + "temp.mp3";
using (Stream stream = assembly.GetManifestResourceStream("YourAssemblyName.music.mp3"))
using (Stream tmp = new FileStream(tmpMP3, FileMode.Create))
{
byte[] buffer = new byte[32 * 1024];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// Creates a temporary MP3 file in the executable directory
tmp.Write(buffer, 0, read);
}
}
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
myplayer.URL = tmpMP3;
myplayer.controls.play();
// Checks the state of the player, and sends the temp file path for deletion
myplayer.PlayStateChange += (NewState) =>
{
Myplayer_PlayStateChange(NewState, tmpMP3);
};
private static void Myplayer_PlayStateChange(int NewState, string tmpMP3)
{
if (NewState == (int)WMPPlayState.wmppsMediaEnded)
{
// Deletes the temp MP3 file
File.Delete(tmpMP3);
}
}
感谢您的帮助,让我们有更多的方式来做到这一点!顺便说一下,我注意到,该文件可以嵌入到exe文件中吗?在属性/建筑行动 - 嵌入资源?如果我是对的,我怎么能把它叫做myplayer.URL? – ERS
请参阅我的编辑以了解如何完成此操作。 –
再一次,谢谢! – ERS