尝试使用 播放 mp3 文件mciSendString
时,请通过以下命令:
open "{FileName}" [type mpegvideo] alias {AliasName}
//尝试了有和没有type mpegvideo
和
play {AliasName}
我得到错误MCIERR_CANNOT_LOAD_DRIVER : 'Unknown problem while loading the specified device driver'
。
在这篇文章中读到您需要安装 MP3 编解码器,但我确实有一个,所以这不是问题。
在四处寻找之后,试图找出问题所在,我偶然发现了这个项目,它是一个使用的音频播放器mciSendString
,并决定尝试一下,看看是否会出现同样的问题,有趣的是它工作得很好,可以播放 mp3 文件。 ..那是什么问题,为什么在我的项目中不起作用。
这是代码(这只是测试代码,如果没有足够的异常处理,请见谅):
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Test
{
unsafe class Program
{
[DllImport("winmm.dll", SetLastError = true)]
public static extern bool mciGetErrorString([In] int error, [In, Out] char[] buffer, [In] int bufferCount);
[DllImport("winmm.dll", SetLastError = true)]
public static extern int mciSendString([In] string command, [Optional, In, Out] char[] returnBuffer, [Optional, In] int returnBufferCount, [Optional, In] IntPtr hNotifyWindow);
static void Main(string[] args)
{
Play(@"D:\Audio\simple_beat.mp3");
Console.ReadLine();
Close();
}
static void Play(string fileName)
{
Close();
if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
{
int error = mciSendString($"open \"{fileName}\" type mpegvideo alias RandomAudio", null, 0, IntPtr.Zero);
if (error != 0)
{
error = mciSendString($"open \"{fileName}\" alias RandomAudio", null, 0, IntPtr.Zero);
if (error != 0)
{
throw new MciException(error);
}
}
error = mciSendString($"play RandomAudio", null, 0, IntPtr.Zero);
if (error != 0)
{
Close();
throw new MciException(error);
}
}
}
static void Close()
{
var error = mciSendString($"close RandomAudio", null, 0, IntPtr.Zero);
if (error != 0)
{
throw new MciException(error);
}
}
class MciException : SystemException
{
public MciException(int error)
{
var buffer = new char[128];
if (mciGetErrorString(error, buffer, 128))
{
_message = new string(buffer);
return;
}
_message = "An unknown error has occured.";
}
public override string Message
{
get
{
return _message;
}
}
private string _message;
}
}
}