無外部控件製作多媒體播放器(一)

利用MCI指令製作播放器,簡單實用,很適合於做爲自己軟件的一個附帶功能或背景音樂,正是基於這點需求,我準備分幾個部分來寫:

1、MCI指令的簡單使用;
2、媒體播放的進度控制與音量調節;
3、音樂信息的讀取,包括MP3(ID3V1 & ID3V2)與ASF(WMA & WMV)等;
4、音樂列表的建立與保存(M3U格式)

本來主要是想寫播放音樂的,舉個播放視頻的例子,沒什麼別的意思,只是感覺播放音樂實在是簡單,沒什麼可寫,同時也是爲了說明,MCI放視頻也是可以的。

Private Const WS_CHILD = &H40000000
Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long
Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long
Private Declare Function SetWindowPos Lib "user32" (ByVal hWnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Private Function ShortName(LName As String) As String
    '取得短文件名
    Dim s As String, i As Long
    i = 512
    s = Space$(i)
    GetShortPathName LName, s, i
    ShortName = Left$(s, InStr(1, s, vbNullChar) - 1)
End Function

Private Function PlayMCI(Cmd As String, Optional ReturnStr As String) As Long
    '播放MCI
    Dim s As String
    s = Space$(256)
    PlayMCI = mciSendString(Cmd, s, 256, 0)
    ReturnStr = Left$(s, InStr(1, s, vbNullChar) - 1)
End Function

Private Function ShowVideo(strFileName As String, hwd As Long, x As Long, y As Long, w As Long, h As Long) As Long
    Dim i As Long, s As String
    If Dir(strFileName, vbHidden Or vbReadOnly Or vbSystem) = vbNullString Or strFileName = vbNullString Then Exit Function
    i = PlayMCI("open """ & ShortName(strFileName) & """ alias Song parent " & hwd & " style " & WS_CHILD & " WAIT")
    If i <> 0 Then Exit Function
    i = PlayMCI("STATUS Song WINDOW HANDLE WAIT", s)
    If i <> 0 Then GoTo fail
    i = Val(s)
    If i = 0 Then GoTo fail
    SetWindowPos i, 0, x, y, w, h, 0
    PlayMCI "play Song"
    ShowVideo = i   '若成功返回視頻窗口的句柄
    Exit Function
fail:
    PlayMCI "close Song"
End Function

Private Sub cmdPlay_Click()
    i=ShowVideo("h:/1.wmv", Me.hWnd, 0, 0, 100, 100)
   '返回的這個句柄,很有用的,可用於移動窗口位置,或SubClass它,加上彈出菜單,響應鼠標動作等
    If i <> 0 Then
        cmdPlay.Enabled = False
        cmdStop.Enabled = True
    End If
End Sub
Private Sub cmdStop_Click()
    PlayMCI "close Song"
    cmdPlay.Enabled = True
    cmdStop.Enabled = False
End Sub

Private Sub Form_Load()
    Me.ScaleMode = 3
    cmdPlay.Enabled = True
    cmdStop.Enabled = False
    cmdPlay.Caption = "播放"
    cmdStop.Caption = "停止"
End Sub
Private Sub Form_Unload(Cancel As Integer)
    PlayMCI "close Song"
End Sub

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章