Play any audio file using VBA Excel

前端 未结 5 1629
独厮守ぢ
独厮守ぢ 2021-01-26 20:52

I have a piece of code which can read most audio files (including wav, mp3, midi...), but it won\'t work if there are spaces in the path or File name.

so I have to revert

5条回答
  •  攒了一身酷
    2021-01-26 21:33

    The following solution works without having to copy the file.

    It incorporates your code together with code from osknows in Get full path with Unicode file name with the idea from Jared above...

    Option Explicit
    
    Private Declare PtrSafe Function mciSendString Lib "winmm.dll" Alias _
       "mciSendStringA" (ByVal lpstrCommand As String, ByVal _
       lpstrReturnString As Any, 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 lBuffer As Long) As Long
    
    Private sMusicFile As String
    Dim Play, a
    
    Public Sub Sound2(ByVal File$)
    
    sMusicFile = GetShortPath(File)
    
    Play = mciSendString("play " & sMusicFile, 0&, 0, 0)
    If Play <> 0 Then 'this triggers if can't play the file
       'Play = mciSendString("'play " & sMusicFile & "'", 0&, 0, 0) 'i tried this aproach, but doesn't seem to work
    End If
    
    End Sub
    
    
    Public Sub StopSound(Optional ByVal FullFile$)
    Play = mciSendString("close " & sMusicFile, 0&, 0, 0)
    End Sub
    
    
    Public Function GetShortPath(ByVal strFileName As String) As String
        'KPD-Team 1999
        'URL: [url]http://www.allapi.net/[/url]
        'E-Mail: [email]KPDTeam@Allapi.net[/email]
        Dim lngRes As Long, strPath As String
        'Create a buffer
        strPath = String$(165, 0)
        'retrieve the short pathname
        lngRes = GetShortPathName(strFileName, strPath, 164)
        'remove all unnecessary chr$(0)'s
        GetShortPath = Left$(strPath, lngRes)
    End Function
    

提交回复
热议问题