Jump to content

QBasic/Sound

From Wikibooks, open books for an open world

QBasic has three ways of making sounds.

  • BEEP command
  • SOUND command
  • PLAY command

Earlier used as PRINT CHR$(07) the now available BEEP command makes a beep noise. It is commonly used to attract attention, when some important message is being displayed.

'Syntax example
BEEP 
PRINT CHR$(07)

The two commands , as can be seen by running this program on a computer, are exactly the same.


SOUND

[edit | edit source]

The SOUND command produces sound of a specific frequency for a specific duration from the PC Speaker. Only one sound can be played at a time. If multiple SOUND statements are issued sequentially, every statement after the first will not execute until after the previous one finishes.

Syntax

[edit | edit source]
SOUND f, d
  • f - Frequency in Hertz, ranges from 37 to 32767
  • d - Duration in ticks, ranges from 0 to 65535, there are 18.2 ticks per second

Example

[edit | edit source]
SOUND 100, 18.2

Plays a 100 hertz wave for 18.2 ticks, about 1 seconds.

The lowest frequency allowed by QBasic is 37 Hz, which is roughly a D in the 2nd octave. The highest frequency is 32 767 Hz, but this tone can not be heard, because the normal human hearing range ends at 20 000 Hz.

A secondary function of the SOUND command is to use it to control time in a program.

   For x% = 1 TO 10
    Print x%
    Sound 3200,18.2
   NEXT

This program will print the numbers 1 to 10, with a 1 second delay between each number,and play a sound of 3200hz having interval of 1 second.(edited by FalcoN)

The PLAY command is for playing musical notes,octave. It can only play one note at a time.

More than that the play command can play a complex stored "song" This is accomplished through the use of a song string. For string command detail, see QBasic/Appendix#PLAY.

Simple Musical Keyboard In Qbasic

[edit | edit source]
rem Music keyboard
do 
note$ = inkey$
select case ucase$(note$)
case "A"
Play "A"

case "B"
Play "B"

case "C"
Play "C"

case "D"
Play "D"

case "E"
Play "E"

case "F"
Play "F"

case "G"
Play "G"

end select 

loop until ucase$(note$) = "Q"

end

This code uses a select case command to check values of note$ . Ucase$ is used to maintain that there be no difference if Caps Lock is applied. The play command is used to play different notes. The other features of play have not been used here.