QB64.com

QB64 is a modern extended BASIC programming language that retains QBasic/QuickBASIC 4.5 compatibility and compiles native binaries for Windows, Linux, and macOS.

The _SNDRAW statement plays sound wave sample frequencies created by a program.

Syntax

_SNDRAW leftSample[, rightSample][, pipeHandle&]

Parameter(s)

Description

Example(s)

Sound using a sine wave with _SNDRAW Amplitude * SIN(8 * ATN(1) * Duration * (Frequency / _SNDRATE))


FREQ = 400                             'any frequency desired from 36 to 10,000
Pi2 = 8 * ATN(1)                       '2 * pi 
Amplitude = .3                         'amplitude of the signal from -1.0 to 1.0
SampleRate = _SNDRATE                  'sets the sample rate
FRate = FREQ / SampleRate'
FOR Duration = 0 TO 5 * SampleRate     'play 5 seconds
        _SNDRAW Amplitude * SIN(Pi2 * Duration * FRate)            'sine wave
       '_SNDRAW Amplitude * SGN(SIN(Pi2 * Duration * FRate))       'square wave
NEXT
DO: LOOP WHILE _SNDRAWLEN
END 

Explanation: The loop Duration is determined by the number of seconds times the _SNDRATE number of samples per second. Square waves can use the same formula with Amplitude * SGN(SIN(8 * ATN(1) * Duration * (Frequency/_SNDRATE))).

A simple ringing bell tone that tapers off.


t = 0
tmp$ = "Sample = ##.#####   Time = ##.#####"
LOCATE 1, 60: PRINT "Rate:"; _SNDRATE
DO
  'queue some sound
  DO WHILE _SNDRAWLEN < 0.1             'you may wish to adjust this    
    sample = SIN(t * 440 * ATN(1) * 8)  '440Hz sine wave (t * 440 * 2π)   
    sample = sample * EXP(-t * 3)       'fade out eliminates clicks after sound
    _SNDRAW sample
    t = t + 1 / _SNDRATE                'sound card sample frequency determines time
  LOOP

  'do other stuff, but it may interrupt sound
  LOCATE 1, 1: PRINT USING tmp$; sample; t
LOOP WHILE t < 3.0                      'play for 3 seconds

DO WHILE _SNDRAWLEN > 0                 'Finish any left over queued sound!
LOOP
END 

Routine uses _SNDRAW to display and play 12 notes from octaves 1 through 9.


DIM SHARED rate&
rate& = _SNDRATE
DO
  PRINT "Enter the octave 1 to 8 (0 quits!):";
  oct% = VAL(INPUT$(1)): PRINT oct%
  IF oct% = 0 THEN EXIT DO
  octave = oct% - 4 '440 is in the 4th octave, 9th note
  COLOR oct% + 1
  PRINT USING "Octave: ##"; oct%
  FOR Note = 0 TO 11  'notes C to B
    fq = FreQ(octave, Note, note$)
    PRINT USING "#####.## \\"; fq, note$
    PlaySound fq
    IF INKEY$ > "" THEN EXIT DO
  NEXT
LOOP
END

FUNCTION FreQ (octave, note, note$)
FreQ = 440 * 2 ^ (octave + (note + 3) / 12 - 1) '* 12 note octave starts at C (3 notes up)
note$ = MID$("C C#D D#E F F#G G#A A#B ", note * 2 + 1, 2)
END FUNCTION

SUB PlaySound (frq!)    ' plays sine wave fading in and out
SndLoop! = 0
DO WHILE SndLoop! < rate&
  _SNDRAW SIN((2 * 4 * ATN(1) * SndLoop! / rate&) * frq!) * EXP(-(SndLoop! / rate&) * 3)
  SndLoop! = SndLoop! + 1
LOOP
DO: LOOP WHILE _SNDRAWLEN   'flush the sound playing buffer
END SUB 

See Also