你好我是c#的新手,我正在做一个我需要播放mp3文件的小游戏。
我一直在搜索这个并使用wmp来做,像这样:
onScroll
我能够使用mp3文件的完整路径成功播放文件。问题是我找不到直接从项目文件夹中使用文件的方法,我的意思是,如果我将项目复制到另一台计算机,mp3文件的路径将无效,并且不会播放声音。我觉得我现在处于死胡同,所以如果有人能帮助我,我会很感激!提前致谢
答案 0 :(得分: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();
答案 1 :(得分:0)
这适用于任何机器,前提是你的mp3& exe在同一个文件夹中。
string mp3Path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + mp3filename
答案 2 :(得分: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);
}
}