Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local SAMPLE_RATE = 44100
- -- Karplus-Strong generator
- local function tick(buffer, attenuation)
- local previous_position = buffer.current
- local first = buffer[buffer.current]
- buffer.current = buffer.current + 1
- if buffer.current > buffer.n then
- buffer.current = 1
- end
- local second = buffer[buffer.current]
- local value = attenuation * (second + first) / 2
- buffer[previous_position] = value
- return value
- end
- local function create_buffer(frequency)
- local buffer_size = math.floor(SAMPLE_RATE / frequency + 0.5)
- local buf = {}
- for i = 1, buffer_size do
- buf[i] = math.random(-1, 1)
- end
- buf.current = 1
- buf.n = buffer_size
- return buf
- end
- local function generate_sound(frequency, length, attenuation)
- local sound = {}
- local ringbuffer = create_buffer(frequency)
- local length_in_samples = length * SAMPLE_RATE
- for i = 1, length_in_samples do
- sound[i] = tick(ringbuffer, attenuation)
- end
- return sound
- end
- -- Convert array to love2d's SoundData
- local function array_to_sound_data(array)
- local data = love.sound.newSoundData(#array, SAMPLE_RATE, 16, 1)
- for i, v in ipairs(array) do
- data:setSample(i-1, v)
- end
- return data
- end
- local attenuation = 1
- local notes = {}
- do
- local base_frequency = 200
- local keys = {"q", "2", "w", "3", "e", "r", "5", "t", "6", "y", "7", "u", "i"}
- for i, key in pairs(keys) do
- notes[key] = base_frequency * math.pow(2, i/12)
- end
- end
- function love.keypressed(key)
- if key == "up" then
- attenuation = attenuation + 0.01
- if attenuation > 1 then
- attenuation = 1
- end
- elseif key == "down" then
- attenuation = attenuation - 0.01
- if attenuation < 0 then
- attenuation = 0
- end
- end
- local frequency = notes[key]
- if frequency then
- local sound = generate_sound(frequency, 5, attenuation)
- local soundData = array_to_sound_data(sound)
- local audiosrc = love.audio.newSource(soundData)
- love.audio.stop()
- love.audio.play(audiosrc)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment