StdAudio
is part of Sedgewick’s standard library that is used to play, manipulate, and synthesize sound.sin
function repeats itself once every \(2\pi\) units, so if we measure \(t\) in seconds and plot \(\sin(2\pi t \times 440)\), we get a curve that oscillates 440 times per second.note | i | frequency |
---|---|---|
A | 0 | 440.00 |
A♯ or B♭ | 1 | 466.16 |
B | 2 | 493.88 |
C | 3 | 523.25 |
C♯ or D♭ | 4 | 554.37 |
D | 5 | 587.33 |
D♯ or E♭ | 6 | 622.25 |
E | 7 | 659.26 |
F | 8 | 698.46 |
F♯ or G♭ | 9 | 739.99 |
G | 10 | 783.99 |
G♯ or A♭ | 11 | 830.61 |
A | 12 | 880.00 |
play
function of StdAudio
takes a DoubleArray
as its argument and plays the sound represented by that array on your computer.StdAudio
library has these functions
close(): Unit
—closes standard audioloop(filename: String): Unit
—loops the audio file filename
(in .wav, .mid, or .au format) in a background threadplay(sample: Double): Unit
—plays sample
for 1/44,100 secondplay(samples: DoubleArray): Unit
—plays the samples
arrayplay(filename: String): Unit
—plays the audio file filename
(in .wav, .mid, or .au format) in a background threadread(filename: String): DoubleArray
—reads the audio samples from the file filename
(in .wav or .au format) and returns them as a double array with values between -1.0 and +1.0save(filename: String, samples: DoubleArray): Unit
—saves samples
to the audio file filename
(using .wav or .au format).SAMPLE_RATE
to be 44100.Here is a simple-minded music player
import kotlin.math.*
import StdAudio.*
fun main(args: Array<String>) {
val sc = java.util.Scanner(System.`in`)
// Read a tune from standard input and play it.
while (sc.hasNext()) {
// Read and play one note.
val pitch = sc.nextInt()
val duration = sc.nextDouble()
val hz = 440 * 2.0.pow(pitch / 12.0)
val n = (SAMPLE_RATE * duration).toInt()
val a = DoubleArray(n+1) { sin(2*PI * it * hz / SAMPLE_RATE) }
play(a)
}
}
It reads lines from input of the form
7 0.25
6 0.25
...
meaning the 7th note relative to concert A for 0.25 second; the 6th note relative to concert A for 0.25 second, etc, and successively plays them.