2017-02-10 91 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