VB.Net 如何播放 MP3 或 MIDI 音樂

摘要:VB.Net 如何播放 MP3 或 MIDI 音樂

VB.Net 播放 MP3 或 MIDI 音樂

一般 WAV 可用 My.Computer.Audio.Play(location) 播放


Imports System.IO
Imports System.Text

Public Class Form1

    ' 宣告 API 
    Private Declare Function mciSendStringA Lib "winmm.dll" (
        ByVal lpstrCommand As String,
        ByVal lpstrReturnString As String,
        ByVal uReturnLength As Int32,
        ByVal hwndCallback As Int32) As Int32

    Private Declare Auto Function GetShortPathName Lib "kernel32" ( _
        ByVal longPath As String,
        ByVal shortPath As StringBuilder,
        ByVal shortBufferSize As Int32) As Int32

    Private Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click
        PlayMediaFile("D:\My Music\死了都要改.mp3") ' 播放 MP3 音樂
        '或
        'PlayMidiFile("C:\頑皮豹.mid") ' 播放 MIDI 音樂
    End Sub

    Private Sub Button2_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button2.Click
        StopMedia() ' 停止播放
    End Sub

    Private Sub Button3_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button3.Click
        PauseMedia() ' 暫停播放
    End Sub

    Private Sub Button4_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button4.Click
        ContinueMedia()  ' 繼續播放
    End Sub

    '播放媒體檔案
    Private Function PlayMediaFile(ByVal mediaFile As String) As Boolean
        If File.Exists(mediaFile) Then
            mediaFile = ConvertToShortPathName(mediaFile)
            mciSendStringA("stop music", "", 0, 0)
            mciSendStringA("close music", "", 0, 0)
            mciSendStringA(String.Format("open {0} alias music", mediaFile), "", 0, 0)
            PlayMediaFile = mciSendStringA("play music", "", 0, 0) = 0
        End If
    End Function

    '取得短路徑及檔名
    Private Function ConvertToShortPathName(fileName As String) As String
        Dim shortName As New StringBuilder(256)
        GetShortPathName(fileName, shortName, shortName.Capacity)
        Return shortName.ToString
    End Function

    ' 停止播放
    Private Function StopMedia() As Boolean
        StopMedia = mciSendStringA("stop music", "", 0, 0) = 0
        mciSendStringA("close music", "", 0, 0)
    End Function

    ' 暫停播放
    Private Function PauseMedia() As Boolean
        Return mciSendStringA("pause music", "", 0, 0) = 0
    End Function

    ' 繼續播放
    Private Function ContinueMedia() As Boolean
        Return mciSendStringA("play music", "", 0, 0) = 0
    End Function

End Class