How to play continuous background music
Last updated: December 07, 1997
Article ID: RS23119
The information in this article applies to:
SUMMARY
This article explains how to play background music continuously within your program, providing an aural backdrop for your multimedia or game project.
MORE INFORMATION
Visual Basic provides the MCI32.OCX Standard control which enables you to play many types of multimedia files such as .AVI, .WAV, and .MID files. Most games and multimedia titles use .mid files for background sounds or music and .wav files for action sounds (such as when you click on a linkable button).
While this control is extremely functional, it has many limitations. You must also distribute the custom control file with your application. The Win32 API contains various API functions which enables you to perform most of these same functions.
Step-by-Step Example
Option Explicit
' multimedia functions
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
Public IsMusicOn As Boolean
Public RetValue As Long
Private Sub Form_Load()
IsMusicOn = True
' open the background music file
RetValue = mciSendString("OPEN " & App.Path & "\yourfile.mid TYPE SEQUENCER ALIAS BackgroundMusic", "", 0, 0)
End Sub
Private Sub Form_Unload(Cancel As Integer)
IsMusicOn = False
' tell the midi file to stop playing
RetValue = mciSendString("CLOSE BackgroundMusic", "", 0, 0)
End Sub
Private Sub Timer1_Timer()
Dim MCIStatusLen As Integer
Dim MCIStatus As String
' check status of background music
If IsMusicOn = True Then
' see if the music is still playing
MCIStatusLen = 15
MCIStatus = String(MCIStatusLen + 1, " ")
RetValue = mciSendString("STATUS BackgroundMusic MODE", MCIStatus, MCIStatusLen, 0)
If UCase(Left$(MCIStatus, 7)) = "STOPPED" Then
' restart music from the beginning again
RetValue = mciSendString("PLAY BackgroundMusic FROM 0", "", 0, 0)
End If
End If
End Sub
Notes
Many applications provide the user with the means of enabling/disabling background music via an options menu. You can emulate this by sub-calling the code in the forms load/unload events when the user chooses an option from a menu or optional dialog box.
THE INFORMATION PROVIDED IN THE RABIT SOFTWARE KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. RABIT SOFTWARE DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL RABIT SOFTWARE OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF RABIT SOFTWARE OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.