Advertisement
Snusmumriken

Love2d piano

Feb 26th, 2018
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. local piano = {}
  2. piano.freq = {
  3. ['C'] = 32.703,
  4. ['C#'] = 34.648,
  5. ['D'] = 36.708,
  6. ['D#'] = 38.891,
  7. ['E'] = 41.203,
  8. ['F'] = 43.654,
  9. ['F#'] = 46.249,
  10. ['G'] = 48.999,
  11. ['G#'] = 51.913,
  12. ['A'] = 55,
  13. ['A#'] = 58.27,
  14. ['B'] = 61.735,
  15. }
  16.  
  17. function piano:getFrequency(note, octave)
  18. local freq = self.freq[note:upper()]
  19. if not freq then return end
  20. return freq * 2 ^ ((octave or 3) - 1)
  21. end
  22.  
  23. local function Snusmumriken(freq, ampl, rate)
  24. local sin = math.sin
  25. local tau = math.pi * 2
  26. local freq = freq or 400
  27. local ampl = ampl or 1
  28. local rate = rate or 44100
  29. local dt = 1/rate
  30.  
  31. local time = 0
  32. return function(fr)
  33. time = time + (fr or freq) * dt
  34. return sin(tau * time) * ampl
  35. end
  36. end
  37.  
  38. piano.sin = Snusmumriken()
  39.  
  40. piano.soundData = false
  41.  
  42. function piano:play(note)
  43. local octave = 4
  44. local samples = 441000
  45.  
  46. local freq = self:getFrequency(note, octave)
  47. if not freq then return end
  48.  
  49.  
  50. local data = love.sound.newSoundData(samples, _, 8, 1)
  51.  
  52. for i = 1, samples - 1 do
  53. local snus2 = .4
  54. data:setSample(i, self.sin(freq) * snus2)
  55. end
  56.  
  57. self.soundData = data
  58.  
  59. local source = love.audio.newSource(data)
  60. print('Play!', note)
  61.  
  62. source:play()
  63. end
  64.  
  65. function love.keypressed(key)
  66. if love.keyboard.isDown('lshift', 'rshift') then
  67. key = key..'#'
  68. end
  69. piano:play(key)
  70. end
  71.  
  72.  
  73. function love.draw()
  74. local data = piano.soundData
  75. if not data then return end
  76.  
  77. local w, h = love.graphics.getDimensions()
  78.  
  79.  
  80. local count = data:getSampleCount()
  81. local function graph(i)
  82. return data:getSample(math.floor(i*count/w))
  83. end
  84.  
  85.  
  86. local half = 0.2
  87. love.graphics.line(0, h*half, w, h*half)
  88.  
  89. for i = 1, w-1 do
  90. local x, y = i-1, h*(half + graph(i-1)*half)
  91. local x2, y2 = i, h*(half + graph(i)*half)
  92.  
  93. love.graphics.line(x, y, x2, y2)
  94. end
  95. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement