Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local piano = {}
- piano.freq = {
- ['C'] = 32.703,
- ['C#'] = 34.648,
- ['D'] = 36.708,
- ['D#'] = 38.891,
- ['E'] = 41.203,
- ['F'] = 43.654,
- ['F#'] = 46.249,
- ['G'] = 48.999,
- ['G#'] = 51.913,
- ['A'] = 55,
- ['A#'] = 58.27,
- ['B'] = 61.735,
- }
- function piano:getFrequency(note, octave)
- local freq = self.freq[note:upper()]
- if not freq then return end
- return freq * 2 ^ ((octave or 3) - 1)
- end
- local function Snusmumriken(freq, ampl, rate)
- local sin = math.sin
- local tau = math.pi * 2
- local freq = freq or 400
- local ampl = ampl or 1
- local rate = rate or 44100
- local dt = 1/rate
- local time = 0
- return function(fr)
- time = time + (fr or freq) * dt
- return sin(tau * time) * ampl
- end
- end
- piano.sin = Snusmumriken()
- piano.soundData = false
- function piano:play(note)
- local octave = 4
- local samples = 441000
- local freq = self:getFrequency(note, octave)
- if not freq then return end
- local data = love.sound.newSoundData(samples, _, 8, 1)
- for i = 1, samples - 1 do
- local snus2 = .4
- data:setSample(i, self.sin(freq) * snus2)
- end
- self.soundData = data
- local source = love.audio.newSource(data)
- print('Play!', note)
- source:play()
- end
- function love.keypressed(key)
- if love.keyboard.isDown('lshift', 'rshift') then
- key = key..'#'
- end
- piano:play(key)
- end
- function love.draw()
- local data = piano.soundData
- if not data then return end
- local w, h = love.graphics.getDimensions()
- local count = data:getSampleCount()
- local function graph(i)
- return data:getSample(math.floor(i*count/w))
- end
- local half = 0.2
- love.graphics.line(0, h*half, w, h*half)
- for i = 1, w-1 do
- local x, y = i-1, h*(half + graph(i-1)*half)
- local x2, y2 = i, h*(half + graph(i)*half)
- love.graphics.line(x, y, x2, y2)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement