Created
November 12, 2013 05:35
-
-
Save tkojitu/7426014 to your computer and use it in GitHub Desktop.
SoundGraph.rb
This file contains hidden or 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
include Java | |
import javax.swing.SwingUtilities | |
import javax.swing.JFrame | |
import javax.swing.JPanel | |
import javax.swing.BorderFactory | |
import java.awt.Color | |
import java.awt.Dimension | |
import java.awt.Graphics | |
class SoundGraph | |
include java.lang.Runnable | |
SAMPLING_RATE = 44000 | |
PI2 = Math::PI * 2 | |
AMPLITUDE = 500 | |
def createAndShowGUI | |
# samples = makeSinWave | |
samples = makeSquareWave | |
f = JFrame.new("Swing Paint Demo") | |
f.setDefaultCloseOperation(JFrame::EXIT_ON_CLOSE) | |
f.add(SoundGraphPanel.new(samples)) | |
f.pack | |
f.setVisible(true) | |
end | |
def run | |
createAndShowGUI | |
end | |
def makeSinWave | |
fr = 440 | |
samples = [] | |
ph = 0.0 | |
SAMPLING_RATE.times do |i| | |
samples[i] = (AMPLITUDE * Math::sin(ph)).to_i | |
ph += PI2 * fr / SAMPLING_RATE | |
end | |
return samples | |
end | |
def makeSquareWave | |
fr = 440.0 | |
samples = [] | |
len = SAMPLING_RATE / fr | |
SAMPLING_RATE.times do |i| | |
if i % len < len / 2 | |
samples[i] = AMPLITUDE | |
else | |
samples[i] = -AMPLITUDE | |
end | |
end | |
return samples | |
end | |
end | |
class SoundGraphPanel < JPanel | |
def initialize(samples) | |
super() | |
@samples = samples | |
setBorder(BorderFactory.createLineBorder(Color::black)) | |
end | |
def getPreferredSize | |
return Dimension.new(1024, 1024) | |
end | |
def paintComponent(g) | |
super(g) | |
@samples.each_with_index do |value, i| | |
g.drawLine(i, value + 510, i, value + 510) | |
end | |
end | |
end | |
SwingUtilities.invokeLater(SoundGraph.new) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment