我使用此代码为我的游戏播放MIDI文件,但我听不到扬声器发出的任何声音。你能帮我吗?这是一种紧急情况,请...... 我的扬声器已打开;)
[DllImport("winmm.dll", EntryPoint="mciSendStringA")]
private static extern long mciSendString(string lpstrCommand, string lpstrReturnString, long uReturnLength, long hwndCallback);
public static long PlayMidiFile(string MidiFile)
{
long lRet = -1;
if (File.Exists(MidiFile))
{
lRet = mciSendString("stop midi", "", 0, 0);
lRet = mciSendString("close midi", "", 0, 0);
lRet = mciSendString(("open sequencer!"
+ (MidiFile + " alias midi")), "", 0, 0);
lRet = mciSendString("play midi", "", 0, 0);
return lRet;
}
else
{
//Error Message
return lRet;
}
}
答案 0 :(得分:4)
我不确定你的winmm.dll的实现,但我有一个经过测试和运行的代码。
我从这个开源项目得到了源代码:Tea Timer。
代码的实现非常简单,如下所示。希望它有所帮助。
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace TeaTimer
{
/// <summary>
/// MCIPlayer is based off code by Slain.
/// Found here: http://www.sadeveloper.net/Articles_View.aspx?articleID=212
/// </summary>
public class MCIPlayer
{
private static readonly string sAlias="TeaTimerAudio";
[DllImport("winmm.dll")]
private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);
[DllImport("Winmm.dll")]
private static extern long PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
public static void Play(string sFile)
{
_Open(sFile);
_Play();
}
public static void Stop()
{
_Close();
}
private static void _Open(string sFileName)
{
if(_Status()!="")
_Close();
string sCommand = "open \"" + sFileName + "\" alias "+sAlias;
mciSendString(sCommand, null, 0, IntPtr.Zero);
}
private static void _Close()
{
string sCommand = "close "+sAlias;
mciSendString(sCommand, null, 0, IntPtr.Zero);
}
private static void _Play()
{
string sCommand = "play "+sAlias;
mciSendString(sCommand, null, 0, IntPtr.Zero);
}
private static string _Status()
{
StringBuilder sBuffer = new StringBuilder(128);
mciSendString("status "+sAlias+" mode", sBuffer, sBuffer.Capacity, IntPtr.Zero);
return sBuffer.ToString();
}
}
}
编辑:这是您播放和停止音乐文件的方式:
public static void playSound(string sFile)
{
//WavPlay.WavPlayer.Play(sFile);
MCIPlayer.Play(sFile);
}
public static void stopSound()
{
//WavPlay.WavPlayer.StopPlay();
MCIPlayer.Stop();
}
答案 1 :(得分:1)
我曾经使用过这个定义......
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
public static extern void mciSendStringA(string lpstrCommand, string lpstrReturnString, long uReturnLength, long hwndCallback);
...在.Net 3.5但在.Net 4.0中给了我和不平衡的pinvoke异常!我通过使用它来修复它......
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
public static extern void mciSendStringA(string lpstrCommand, string lpstrReturnString, int uReturnLength, IntPtr hwndCallback);
...并传递IntPtr.Zero
作为最后一个参数。
唯一的区别是uReturnLength
是int
(而不是long
)而hwndCallback
是IntPtr
(而不是{{1} }})。
希望这会有所帮助......