2017-02-10 117 views
2

你好,我是新來的c#和我正在做一個小遊戲,我需要播放MP3文件。c#,mp3和文件路徑

我一直在尋找這個和使用WMP做到這一點,就像這樣:

WindowsMediaPlayer myplayer = new WindowsMediaPlayer(); 
    myplayer.URL = @"c:\somefolder\project\music.mp3"; 
    myplayer.controls.play(); 

我能夠與MP3文件的完整路徑成功播放文件。問題是我找不到直接從項目文件夾使用該文件的方法,我的意思是,如果我將該項目複製到另一臺計算機,則mp3文件的路徑將失效並且不會播放聲音。我覺得我現在處於死衚衕,所以如果有人能幫助我,我將不勝感激!在此先感謝

回答

0

使用另一個簡單的辦法是:

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); 
    } 
} 
+0

感謝您的幫助,讓我們有更多的方式來做到這一點!順便說一下,我注意到,該文件可以嵌入到exe文件中嗎?在屬性/建築行動 - 嵌入資源?如果我是對的,我怎麼能把它叫做myplayer.URL? – ERS

+0

請參閱我的編輯以瞭解如何完成此操作。 –

+0

再一次,謝謝! – ERS

0

將MP3文件添加到您的項目。同時將其標記爲始終複製到輸出文件夾。在這裏你有一個如何做到這一點的教程(How to include other files to the output directory in C# upon build?)。然後,你可以參考這種方式:

你必須使用:

using System.Windows.Forms; 

然後你就可以使用這樣的:

WindowsMediaPlayer myplayer = new WindowsMediaPlayer(); 
myplayer.URL = Application.StartupPath + "\music.mp3"; 
myplayer.controls.play(); 
+0

嗨,只是要多加一個反斜線,像這樣「\ \ music.mp3「,現在它就像一個魅力!謝謝! – ERS

+0

你明白了。不要忘了標記爲答案,如果它有幫助upvote。 :) – NicoRiff

+0

做到這一點,因爲我的聲望小於15,所以我不會公開顯示。 – ERS

0

這應該對任何機器的工作,只要你的MP3 & EXE在同一個文件夾中。

string mp3Path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + mp3filename 
+0

嗨,只是測試你的方式,它也在工作,感謝您的幫助! – ERS