QBasic/Sound

From Wikibooks, open books for an open world
< QBasic
Jump to navigation Jump to search

QBasic has three ways of making sounds.

  • BEEP command
  • SOUND command
  • PLAY command

BEEP[edit]

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]

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]

SOUND f, d
  • f - Frequency in Hertz
  • d - Duration in ticks

Example[edit]

SOUND 100 , 20

Plays a 100 hertz wave for 20 ticks. One second is about 18.2 ticks, so 20 ticks are about 1.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 32000,18.2
   NEXT

This program will print the numbers 1 to 10, with a 1 second delay between each number.

PLAY[edit]

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]

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.