Blitz3D+ Command Reference

PlaySound ( sound )

Parameters

sound - handle of a sound loaded with LoadSound

Description

Plays a loaded sound and returns a channel handle for that playback.

The return value is the important part. A sound is the audio sitting in memory; a channel is one playing instance of it. Play the same explosion three times in quick succession and you get three channels, all running at once, each controllable on its own. That is why you keep the returned handle if you intend to do anything to the sound after it has started.

This is the line where the two families of commands divide. Before you play, the Sound commands - SoundVolume, SoundPan, SoundPitch, LoopSound - set the properties the next playback will start with. After you play, the Channel commands - ChannelVolume, ChannelPan, ChannelPitch, StopChannel, PauseChannel, ChannelPlaying - act on that one running channel and leave the loaded sound alone.

For a one-shot effect you can ignore the return value entirely: PlaySound bang. For anything you will fade, pan as it moves across the screen, or stop early - an engine loop, a siren, a looping ambience - store the channel in a variable.

It returns 0 if the sound handle is 0 or the channel could not be started, so a silent game with no error is usually a failed LoadSound further up. A channel handle is only good while that playback lasts; once it has finished, keeping the old handle around tells you nothing - ask ChannelPlaying.

See also: LoadSound, LoopSound, StopChannel, ChannelVolume, ChannelPlaying, PlayMusic.

Example

; PlaySound Example
; -----------------

Graphics 640,480,0,2
SetBuffer BackBuffer()

; A bullet fired from our little ship
Type bullet
    Field x,y
End Type

; Load the laser sound once, up front
snd_shoot=LoadSound("media/shoot.wav")

shots=0

While Not KeyDown(1)

    ; Space fires: every PlaySound call starts the sound on a FRESH
    ; channel, so rapid shots overlap instead of cutting each other off
    If KeyHit(57) Then
        channel=PlaySound(snd_shoot)
        shots=shots+1
        b.bullet=New bullet
        b\x=320
        b\y=420
    End If

    Cls

    ; Move and draw the bullets
    For b.bullet=Each bullet
        b\y=b\y-8
        If b\y<-10 Then
            Delete b
        Else
            Color 255,255,120
            Rect b\x-1,b\y,3,10
        End If
    Next

    ; The ship
    Color 120,200,255
    Rect 305,445,30,10
    Rect 315,435,10,10

    Color 255,255,255
    Text 0,0,"Space: fire (hold for overlapping shots)   Esc: exit"
    Text 0,20,"channel=PlaySound(snd_shoot)   shots fired: "+shots

    Flip

Wend

End

Index