2010-11-11 98 views
2

我需要播放mp3文件。我想使用winmm.dll(Windows 7)以C#播放音頻文件#

class Program 
{ 
    [DllImport("winmm.dll")] 
    private static extern long mciSendString(string Cmd, StringBuilder StrReturn, int ReturnLength, IntPtr HwndCallback); 

    static void Main(string[] args) 
    { 
     string FileName = @"F:\MUSIC\ROCK.mp3"; 

     string CommandString = "open " + "\"" + FileName + "\"" + " type mpegvideo alias Mp3File"; 
     mciSendString(CommandString, null, 0, IntPtr.Zero); 
     CommandString = "play Mp3File"; 
     mciSendString(CommandString, null, 0, IntPtr.Zero); 
     Console.ReadKey(); 
    } 
} 

但是當我運行我的程序時,什麼都沒有發生。 哪裏出錯?

回答

-1
string FileName = @"F:\MUSIC\ROCK.mp3"; 
mciSendString("open \"" + FileName + "\" type mpegvideo alias MediaFile", null, 0, IntPtr.Zero); 
mciSendString("play " + FileName + " from 0", null, 0, IntPtr.Zero); 

它正常工作。

+0

你問過這個問題的同一個Sergey嗎? – 2010-11-11 18:58:19

-2

這裏,

class Program 
{ 
    public string _command; 
    public bool isOpen; 
    [DllImport("winmm.dll")] 

    public static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback); 

static void Main(string[] args) 
{ 
    string FileName = @"F:\MUSIC\ROCK.mp3"; 
    string _command = "open \"" + sFileName + "\" type mpegvideo alias MediaFile"; 
     mciSendString(_command, null, 0, IntPtr.Zero); 
    isOpen = true; 

    if(isOpen) 
    { 
     _command = "play MediaFile"; 
     if (loop) 
     _command += " REPEAT"; 
     mciSendString(_command, null, 0, IntPtr.Zero); 
     } 
/*For Close the audio 
    _command = "close MediaFile"; 
    mciSendString(_command, null, 0, IntPtr.Zero); 
    isOpen = false; */ 
} 
} 

CommandString中應該是 「玩媒體文件」,而不是 「玩Mp3file」 希望這將有助於.. =]

+0

它需要與'open'命令'alias'子句中使用的設備ID匹配。它在原始代碼中已經做了。 – 2010-11-11 18:53:50

-1

你的命令字符串似乎有一個不正確的類型。

您正在通過type mpegvideo,但該文件不是視頻文件。

對於* .wav文件,正確的音頻類型爲type waveaudio,對於* .mid文件爲type sequencer,對於RedBook CD爲type cdaudio。我沒有看到用MCI播放MP3的任何方式。您可以嘗試完全清除type子句,然後MCI會嘗試檢測它。

此外,你應該捕獲由mciSendString返回的錯誤代碼,它可能會給你更多的信息。

MSDN Reference

2

接受的答案不適用於包含空格的文件路徑。正確的方法是使用您在打開命令中設置的別名:

string FileName = @"F:\MUSIC\ROCK.mp3"; 
mciSendString("open \"" + FileName + "\" type mpegvideo alias thisIsMyTag", null, 0, IntPtr.Zero); 
mciSendString("play thisIsMyTag from 0", null, 0, IntPtr.Zero);