Sine wave: Difference between revisions
Content added Content deleted
Line 126: | Line 126: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
Note that this code does not work on Windows because playing sound from Emacs Lisp data variables is not supported there. |
Note that this code does not work on Windows because playing sound from Emacs Lisp data variables is not supported there. |
||
===8-bit samples=== |
|||
<lang lisp>(defun play-sine (freq dur) |
<lang lisp>(defun play-sine (freq dur) |
||
"Play a sine wave for dur seconds." |
"Play a sine wave for dur seconds." |
||
Line 142: | Line 144: | ||
(play-sine 440 5)</lang> |
(play-sine 440 5)</lang> |
||
While the generated AU sound file is 16 bit, the samples themselves are 8 bit because only their high byte is set by the sine function. Therefore you will hear some faint hiss in the background due to the higher noise floor of 8-bit audio. |
While the generated AU sound file is 16 bit, the samples themselves are 8 bit because only their high byte is set by the sine function. Therefore you will hear some faint hiss in the background due to the higher noise floor of 8-bit audio. |
||
===16-bit samples=== |
|||
This (slightly slower) version of the function creates proper 16-bit samples by setting both high and low bytes, resulting in less playback noise. |
|||
<lang lisp>(defun play-sine16 (freq dur) |
|||
"Play a sine wave for dur seconds." |
|||
(setq header (unibyte-string ; AU header: |
|||
46 115 110 100 ; ".snd" magic number |
|||
0 0 0 24 ; start of data bytes |
|||
255 255 255 255 ; file size is unknown |
|||
0 0 0 3 ; 16 bit PCM samples |
|||
0 0 172 68 ; 44,100 samples/s |
|||
0 0 0 1)) ; mono |
|||
(setq v (mapcar (lambda (x) |
|||
(mod (round (* 32000 (sin (* 2 pi freq x (/ 44100.0))))) 65536)) |
|||
(number-sequence 0 (* dur 44100)))) |
|||
(setq s (apply #'concat header (flatten-list (mapcar (lambda (x) |
|||
(list (unibyte-string (ash x -8)) |
|||
(unibyte-string (mod x 256)))) |
|||
v)))) |
|||
(play-sound `(sound :data ,s))) |
|||
(play-sine16 440 5)</lang> |
|||
=={{header|Go}}== |
=={{header|Go}}== |