A voice recorder in 150 lines of code (well, kinda)


(Update: This post will no longer work as-is with the most recent version of Carousel. You no longer need to include the wav library. Also delete the function `save_wav` below, which is now bundled with Carousel.)

Here's a little voice recorder app that runs within Lua Carousel.


However it comes with some caveats:

  • It requires a new version of Lua Carousel. My existing file organization turned out to be inaccessible to LÖVE's API for playing audio, and I ended up reworking it. The new file organization is much better. Your settings should now migrate much more reliably to any future version (my previous post described some limitations in restoring settings; those limitations should no longer exist). In particular, any tutorial screens you delete will no longer reappear in future versions. (You might want to keep the list of abbreviations around if you're pasting in my blog posts.)

    I still scan the old location, so you should continue to see all your files in the load/save dialogs. Please let me know if you see anything amiss.
  • LÖVE doesn't yet support recording audio on iOS.
  • On Android you'll need to go into the OS's settings and grant the LÖVE app additional permissions to your microphone. I thought about just asking for the permission up front in Lua Carousel, but I always complain when apps ask for permissions without any good reason, and this feels like a place where I can do something about it. "Here's Lua Carousel, please can I listen to your microphone?" Ick.
  • The recorder itself is 150 lines, which is a little larger than previous apps. The scrollbar is starting to get too tiny to easily acquire on my phone.

    (The tablet seems fine. It might be ergonomic with up to 300 lines.)
  • However, the recorder also requires a "library" for saving recordings as .wav files. The library is an additional 130 lines long. I recommend you load it on a separate screen.

Phew! I hope you find it useful. It's been very popular with my kids.

recordings = {}  -- array of string names
cursor_recording = nil
ui_state = {}
-- love.sound.newSoundData requires files under save dir
rdir = 'recordings/'
love.filesystem.createDirectory(rdir)
for _,filename in ipairs(love.filesystem.getDirectoryItems(rdir)) do
  if filename:match('%.wav$') then
    local root, _ = filename:gsub('.wav$', '')
    table.insert(recordings, root)
  end
end
table.sort(recordings)
-- for audio
playing_source = nil
local devices = love.audio.getRecordingDevices()
if #devices == 0 then
  error('no recording devices')
end
recording_device = devices[1]
current_recording = nil
function car.draw()
  ui_state.button_handlers = {}
  local y, h = Menu_bottom+5, 5+Line_height+5
  button(ui_state, 'new recording', {
    x=60, y=y, w=5+App.width('new recording')+5, h=h,
    bg={r=0.7, g=0.7, b=1, a=1},
    icon = function(p)
      color(0,0,0)
      g.print('new recording', p.x+5, p.y+5)
    end,
    onpress1 = new_recording,
  })
  color(0,0,0)
  y = y+h+10
  for i,recording in ipairs(recordings) do
    if recording == current_recording then
      button(ui_state, 'stop', {
        x=35, y=y, w=20, h=20,
        bg={r=1, g=1, b=1},
        icon = function(p)
          color(0,0,0)
          rect('fill', p.x,p.y,p.w,p.h)
        end,
        onpress1 = function() stop_recording(i) end,
      })
    else
      button(ui_state, 'record', {
        x=35, y=y, w=20, h=20,
        bg={r=1, g=1, b=1},
        icon = function(p)
          color(0,0,0)
          circle('fill', p.x+p.w/2,p.y+p.h/2, p.w/2,p.h/2)
        end,
        onpress1 = function() record(i) end,
      })
    end
    if playing_source and not playing_source:isPlaying() then
      playing_source = nil
    end
    if playing_source == nil then
      button(ui_state, 'play', {
        x=65, y=y, w=20, h=20,
        bg={r=1, g=1, b=1},
        icon = function(p)
          color(0,0,0)
          poly('fill', {p.x,p.y, p.x+p.w,p.y+p.h/2, p.x,p.y+p.h})
        end,
        onpress1 = function() play(i) end,
      })
    end
    button(ui_state, 'delete', {
      x=95, y=y, w=20, h=20,
      bg={r=1, g=1, b=1},
      icon = function(p)
        color(1,0,0)
        g.print('x', p.x,p.y)
      end,
      onpress1 = function()
         love.filesystem.remove(rdir..recording..'.wav')
         table.remove(recordings, i)
       end,
      })
    color(0,0,0)
    g.print(recording, 125,y)
    y = y+Line_height+5
  end
end
function car.mousepressed(x,y, b)
  if mouse_press_consumed_by_any_button(ui_state, x,y, b) then
    return
  end
end
function new_recording()
  table.insert(recordings, os.date('%Y-%m-%dT%H-%M-%S'))
end
function save_wav(filename, sounddata)
  local samples = {}
  for i = 0, sounddata:getSampleCount() - 1 do
    local sample = sounddata:getSample(i)
    local n
    local to16bit = sample * 32767
    if (to16bit > 0) then
      n = math.floor(math.min(to16bit, 32767))
    else
      n = math.floor(math.max(to16bit, -32768))
    end
    table.insert(samples, n)
  end
  local w = wav.create_context(filename, "w")
  w.init(sounddata:getChannelCount(), sounddata:getSampleRate(), sounddata:getBitDepth())
  w.write_samples_interlaced(samples)
  w.finish()
end
function record(recording_idx)
  recording_device:start(10*8000, 8000)
  current_recording = recordings[recording_idx]
  playing_source = nil
end
function stop_recording(recording_idx)
  assert(recording_device)
  local recording = recording_device:getData()
  recording_device:stop()
  if recording then
    save_wav(rdir..recordings[recording_idx]..'.wav', recording)
  end
  current_recording = nil
  return
end
function play(recording_idx)
  local filename = rdir..recordings[recording_idx]..'.wav'
  if love.filesystem.getInfo(filename) == nil then return end
  playing_source = audio(love.sound.newSoundData(filename), 'static')
  playing_source:play()
end

Here's the library for saving .wav files. Like I said, I recommend pasting it into a separate screen.

--[[
  Library for simple audio reading, writing and analysing.
  Copyright © 2014, Christoph "Youka" Spanknebel
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
wav = {
  --[[
    Writes audio file in WAVE format with PCM integer samples.
    Function 'create_context' requires a filename and returns a table with the
    following methods:
    - init(channels_number, sample_rate, bits_per_sample)
    - write_samples_interlaced(samples)
    - finish()
  ]]
  create_context = function(filename)
    -- Check function parameters
    if type(filename) ~= "string" then
      error("invalid function parameter, expected string filename", 2)
    end
    local absolute_path = love.filesystem.getSaveDirectory()..'/'..filename
    -- ensure directory exists
    love.filesystem.write(absolute_path, '')
    -- Audio file handle
    local file = io.open(absolute_path, "wb")
    if not file then
      error(string.format("couldn't open file %q", filename), 2)
    end
    -- Byte-string(unsigned integer,little endian)<-Lua-number converter
    local function ntob(n, len)
      local n, bytes = math.max(math.floor(n), 0), {}
      for i=1, len do
        bytes[i] = n % 256
        n = math.floor(n / 256)
      end
      return string.char(unpack(bytes))
    end
    -- Check for integer
    local function isint(n)
      return type(n) == "number" and n == math.floor(n)
    end
    -- Audio meta informations
    local channels_number_private, bytes_per_sample
    -- Return audio handler
    return {
      init = function(channels_number, sample_rate, bits_per_sample)
        -- Check function parameters
        if not isint(channels_number) or channels_number < 1 or
          not isint(sample_rate) or sample_rate < 2 or
          not (bits_per_sample == 8 or bits_per_sample == 16 or bits_per_sample == 24 or bits_per_sample == 32) then
          error("valid channels number, sample rate and bits per sample expected", 2)
        end
        -- Write file type
        file:write("RIFF????WAVE")  -- file size to insert later
        -- Write format chunk
        file:write("fmt ",
              ntob(16, 4),
              ntob(1, 2),
              ntob(channels_number, 2),
              ntob(sample_rate, 4),
              ntob(sample_rate * channels_number * (bits_per_sample / 8), 4),
              ntob(channels_number * (bits_per_sample / 8), 2),
              ntob(bits_per_sample, 2))
        -- Write data chunk (so far)
        file:write("data????")  -- data size to insert later
        -- Set format memory
        channels_number_private, bytes_per_sample = channels_number, bits_per_sample / 8
      end,
      write_samples_interlaced = function(samples)
        -- Check function parameters
        if type(samples) ~= "table" then
          error("samples table expected", 2)
        end
        local samples_n = #samples
        if samples_n == 0 or samples_n % channels_number_private ~= 0 then
          error("valid number of samples expected (multiple of channels)", 2)
        -- Already finished?
        elseif not file then
          error("already finished", 2)
        -- Already initialized?
        elseif file:seek() == 0 then
          error("initialize before writing samples", 2)
        end
        -- All samples are numbers?
        for i=1, samples_n do
          if type(samples[i]) ~= "number" then
            error("samples have to be numbers", 2)
          end
        end
        -- Write samples to file
        local sample
        if bytes_per_sample == 1 then
          for i=1, samples_n do
            sample = samples[i]
            file:write(ntob(sample < 0 and sample + 256 or sample, 1))
          end
        elseif bytes_per_sample == 2 then
          for i=1, samples_n do
            sample = samples[i]
            file:write(ntob(sample < 0 and sample + 65536 or sample, 2))
          end
        elseif bytes_per_sample == 3 then
          for i=1, samples_n do
            sample = samples[i]
            file:write(ntob(sample < 0 and sample + 16777216 or sample, 3))
          end
        else  -- if bytes_per_sample == 4 then
          for i=1, samples_n do
            sample = samples[i]
            file:write(ntob(sample < 0 and sample + 4294967296 or sample, 4))
          end
        end
      end,
      finish = function()
        -- Already finished?
        if not file then
          error("already finished", 2)
        -- Already initialized?
        elseif file:seek() == 0 then
          error("initialize before finishing", 2)
        end
        -- Get file size
        local file_size = file:seek()
        -- Save file size
        file:seek("set", 4)
        file:write(ntob(file_size - 8, 4))
        -- Save data size
        file:seek("set", 40)
        file:write(ntob(file_size - 44, 4))
        -- Finalize file for secure reading
        file:close()
        file = nil
      end
    }
  end,
}

Once you have all that code pasted in and saved, running the recorder requires 3 steps:

1. Run the abbreviations screen. Or if you've deleted that screen, here are the abbreviations this program uses:

g = love.graphics
circle, rect, poly = g.circle, g.rectangle, g.polygon
color = g.setColor
audio = love.audio.newSource

2. Run the screen containing the wav library.

3. Run the screen containing the recorder itself. 

Let me know if you run into issues. Operators are standing by to answer your questions.

Credits

Christoph "Youka" Spanknebel for the wav library.

Intas and Zorg on the LÖVE Forum.

Correction
An earlier version of this post didn't specify the second argument to `audio` (love.audio.newSource). It's not required in practice, but the documentation doesn't mention a default value, and I've since seen strange distracting errors if I run this program without granting LÖVE access to the microphone. Just always include the second arg.

Files

carousel-bc.love 109 kB
Dec 18, 2023
carousel-bc-safe.love 109 kB
Dec 18, 2023

Get Lua Carousel

Leave a comment

Log in with itch.io to leave a comment.