VB中加入背景音乐?

程序一启动便循环播放。wav格式的音乐。
2024-12-20 20:13:52
推荐回答(3个)
回答1:

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 Sub Command1_Click()
'播放
Dim Result As Integer
Dim ReturnStr As String * 1024 '注意,必须指定String的长度
Result = mciSendString("play d:\背景音乐.wav", ReturnStr, 1024, 0)
End Sub

Private Sub Command2_Click()
'停止
Dim Result As Integer
Dim ReturnStr As String * 1024 '注意,必须指定String的长度
rc = mciSendString("close d:\背景音乐.wav", 0, 0, 0)
End Sub

'循环的话,可以检测其状态,如果不想检测的话,用个计时器,Interval设置成播放完需要的时间即可

回答2:

有二个方法,
一用控件.
二用API函数

Private Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub PlayWavFile(strFileName As String, PlayCount As Long, JianGe As Long)
'strFileName 要播放的文件名(带路径)
'playCount 播放的次数
'JianGe 多次播放时,每次的时间间隔
If Len(Dir(strFileName)) = 0 Then Exit Sub
If PlayCount = 0 Then Exit Sub
If JianGe < 1000 Then JianGe = 1000
DoEvents
sndPlaySound strFileName, 16 + 1
Sleep JianGe
Call PlayWavFile(strFileName, PlayCount - 1, JianGe)
End Sub

Private Sub Form_Click()
PlayWavFile "C:\aaa.wav", 1, 1000
End Sub

回答3:

模块部分
Attribute VB_Name = "Module1"
Option Explicit
Declare Function sndPlaySound Lib "winmm" Alias _
"sndPlaySoundA" (ByVal lpszSoundName As String, _
ByVal uFlags As Long) As Long

' flag values for uFlags paramaeter
Public Const SND_SYNC = &H0
Public Const SND_ASYNC = &H1
Public Const SND_NODEFAULT = &H2
Public Const SND_MEMORY = &H4
Public Const SND_LOOP = &H8
Public Const SND_NOSTOP = &H10

窗体按钮部分如下
Private Sub Command1_Click()
Dim rc As String
rc = sndPlaySound("文件路径和名称.wav", SND_ASYNC)
End Sub

Private Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" _
(ByVal lpszSoundName As String, ByVal uFlags As Long) As Long
Const SND_LOOP = &H8
Const SND_ASYNC = &H1

Private Sub Command1_Click()
'循环播放
sndPlaySound "路径和名称.wav", SND_ASYNC Or SND_LOOP
End Sub

Private Sub Command2_Click()
'停止播放
sndPlaySound vbNullString, SND_ASYNC
End Sub