CodeItBetter Programming Another VB Programming Blog

How to play sound

Posted on January 5, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'MultiMedia - How to play sound
Option Explicit
 
Public ds As DirectSound8    'Our DirectSound object
Const Max_Channels = 20      'The maximum number of simultanoes sounds
Dim dsBuffer() As DirectSoundSecondaryBuffer8    'Our SoundBuffers
Dim dsBufferUsed As Integer
 
Public Sub Add3DSound(ByVal nFilename As String, Optional lFrequency, Optional lPan, Optional lVolume)
    'First let's search a free buffer
    Dim nB As Long
    dsBufferUsed = dsBufferUsed + 1
    If dsBufferUsed > Max_Channels Then dsBufferUsed = 0
    nB = dsBufferUsed
 
    Dim dsBuf As DSBUFFERDESC
 
    'First clear the buffer
    If Not (dsBuffer(nB) Is Nothing) Then dsBuffer(nB).Stop
    Set dsBuffer(nB) = Nothing
 
    'Set some flags to the description
    dsBuf.lFlags = DSBCAPS_CTRLFREQUENCY Or DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME
    On Error Resume Next
    'Load file into buffer
    Set dsBuffer(nB) = ds.CreateSoundBufferFromFile(nFilename, dsBuf)
    If Err Then
        Debug.Print "Could not create soundbuffer (" & nFilename & ")"
        Exit Sub
    End If
 
    'If so, add "effects"
    If Not IsMissing(lFrequency) Then dsBuffer(nB).SetFrequency lFrequency
    '100-100000

    If Not IsMissing(lPan) Then dsBuffer(nB).SetPan lPan
    '-10000(left) 0(middle) +10000(right)

    If Not IsMissing(lVolume) Then dsBuffer(nB).SetVolume lVolume
    '-2500 - 0

    'let's play!
    dsBuffer(nB).Play DSBPLAY_DEFAULT
End Sub
 
Public Function Init(dx As DirectX8, nHWnd As Long) As Boolean
    'This one initializes our DSound objects
    On Local Error Resume Next
    Set ds = dx.DirectSoundCreate(vbNullString)    'Create a default DirectSound object

    'We couldn't create the DSound object.  End the app now
    If Err.Number <> 0 Then
        MsgBox "Could not initialize DirectSound." & vbCrLf & "This program will exit.", vbOKOnly Or vbInformation, "Exiting..."
        Init = False
        Exit Function
    End If
    'Set the coop level
    ds.SetCooperativeLevel nHWnd, DSSCL_PRIORITY
 
    ReDim dsBuffer(0 To Max_Channels)
 
    Init = True
    Debug.Print "ModDSOUND3D.Init successfully processed"
End Function
 
Public Sub Destroy()
    'This one kills our DS objects
    On Error Resume Next
    Dim n As Integer
 
    For n = 0 To UBound(dsBuffer)
        Set dsBuffer(n) = Nothing
    Next n
    Set ds = Nothing
    Debug.Print "ModDSOUND3D.Destroy successfully processed"
End Sub
 
'How can I use this:
Private Sub Form_Load()
    ModDSOUND3D.Init modDXGFX8.DirectX, Me.hwnd
    ModDSOUND3D.Add3DSound "sound.wav"
End Sub
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.