使用另一個簡單的辦法是:
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