Last active
April 24, 2021 20:20
-
-
Save siers/1410312 to your computer and use it in GitHub Desktop.
Plays from sol to sol.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
# Primitive NoteFactory. | |
# http://en.wikipedia.org/wiki/Piano_key_frequencies | |
T = 44000 | |
class NoteFactory | |
attr_accessor :notes, :notes_in_octave | |
def initialize | |
@notes = { | |
sol: 47, | |
la: 49, | |
si: 51, | |
do: 52, | |
re: 54, | |
mi: 56, | |
fa: 58 # actually fa with bemol ^_^, else it wouldn't sound right. | |
} | |
@notes_in_octave = 12 | |
end | |
def sin(n) | |
Math.sin(n * 3.14/180) | |
end | |
def note(n) | |
if not n | |
p 'something\'s wrong' | |
exit | |
end | |
freq = 440 * 2 ** ((n - 49.0) / 12) | |
$stderr.write("playing n = #{n}; freq = #{freq}\n") | |
i = 0 | |
q = 360 * freq / T | |
while i < T * 0.74 do | |
tick = (sin(i * q) * 127) + 128 | |
$>.write(tick.to_i.chr) | |
i = i + 1 | |
end | |
end | |
end | |
fac = NoteFactory.new | |
arg, octave = ARGV.flatten.join(" ").scan(/[^ ]+/) | |
if octave | |
octave = octave.to_i * fac.notes_in_octave | |
else | |
octave = 0 | |
end | |
fac.note(fac.notes[arg.to_sym] + octave) | |
__END__ | |
#!/bin/zsh | |
play() { ./dsp.rb "$@" | aplay --rate=44000 2> /dev/null; } | |
for note in sol la si do re mi fa "sol 1"; do play $note; done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment