Tipp 4.13 - MP3 abspielen

Wie kann ich eine MP3 Datei abspielen?

Mit dieser Funktion können Sie eine MP3 Datei abspielen. Kopieren Sie einfach nachfolgenden Quellcode in die Zwischenablage und fügen Sie anschließend den Inhalt der Zwischenablage in ein neues Modul ein. Die Aufrufparameter finden Sie im Quellcode beschrieben.

Api-AufrufeVerwendete Win32-Api-Aufrufe und Typen: GetShortPathName, mciSendString

Beispiel:

Option Explicit
 
Declare Function GetShortPathName Lib "kernel32" Alias _
                "GetShortPathNameA" _
                (ByVal lpszLongPath As String, _
                 ByVal lpszShortPath As String, _
                 ByVal cchBuffer As Long) As Long
 
Declare Function mciSendString Lib "winmm.dll" Alias _
                "mciSendStringA" _
                (ByVal lpszCommand As String, _
                 ByVal lpszReturnString As String, _
                 ByVal cchReturnLength As Long, _
                 ByVal hwndCallback As Long) As Long
 
 
Function Play_MP3(ByVal sMP3File As String, ByVal sAlias As String) As Boolean
 
    Dim bResult As Boolean
    Dim sBuffer As String
    Dim sMCICmd As String
    Dim lResult As Long
'// ========================================================
'// MP3-Pfad in 8.3 DOS-Pfad konvertieren
'// ========================================================
    sBuffer = String(256, 0)
    lResult = GetShortPathName(sMP3File, sBuffer, Len(sBuffer))
 
    If lResult <> 0 Then
        sMP3File = _
        Left$(sBuffer, InStr(sBuffer, vbNullChar) - 1)
    Else
        MsgBox "Ungültiger Dateipfad!", vbExclamation
        Exit Function
    End If
'// ========================================================
'// Datei mittels MCI öffnen
'// ========================================================
    sMCICmd = "open " & sMP3File & " type MPEGVideo alias " & sAlias
 
    If mciSendString(sMCICmd, 0, 0, 0) = 0 Then
        sMCICmd = "play " & sAlias & " from 0"
        Play_MP3 = (mciSendString(sMCICmd, 0, 0, 0) = 0)
    End If
 
End Function
 
Public Sub Stop_MP3(ByVal sAlias As String)
 
    mciSendString "stop " & sAlias, 0, 0, 0
    mciSendString "close " & sAlias, 0, 0, 0
 
End Sub
 
Sub Test()
 
    Play_MP3 "C:\Temp\Test.mp3", "MyAlias"
    Stop_MP3 "MyAlias"
 
End Sub