Skip to content

Instantly share code, notes, and snippets.

@tkojitu
Created December 24, 2011 14:51
Show Gist options
  • Save tkojitu/1517442 to your computer and use it in GitHub Desktop.
Save tkojitu/1517442 to your computer and use it in GitHub Desktop.
play square wave from JRuby.
include Java
java_import javax.sound.sampled.AudioFormat
java_import javax.sound.sampled.DataLine
java_import javax.sound.sampled.SourceDataLine
java_import javax.sound.sampled.AudioSystem
SAMPLE_RATE = 44100
audio_format = AudioFormat.new(SAMPLE_RATE, 8, 1, true, true)
info = DataLine::Info.new(SourceDataLine.java_class, audio_format)
line = AudioSystem::getLine(info)
frequency = 440
amplitude = SAMPLE_RATE / (frequency * 2)
buf = []
SAMPLE_RATE.times do |i|
r = i / amplitude
buf[i] = (r % 2 == 0) ? 5 : -5
end
line.open
line.start
jbuf = buf.to_java(:byte)
line.write(jbuf, 0, jbuf.length)
line.drain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment