lao documentation

lao version 1.1.0 - 20170904


ao.array2string

Converts a lua array of numbers into the byte-string that can be fed to device:play.
It also returns a second value, the buf_size number that device:play will need.

Currently it is restricted to the common case of 16-bit devices.

If there is more than one channel, for example two, then the array should contain the channel samples in the order
  { sample1_left, sample1_right, sample2_left, sample2_right, sample3_left . . . }

string buf, integer buf_size = ao.array2string( { numbers samples }, table sampleFormat )

The sampleFormat table is optional, and can contain the following fields:

Notes

array2string, introduced in 1.2.0, simplifies putting together the string of sample data that device:play will need.

  local buffer = {}
  for i = 0,format.rate do    -- one second
    local sample = 0.75 * math.sin(2*math.pi*freq*i / format.rate)
    buffer[2*i+1] = sample   -- left
    buffer[2*i+2] = sample   -- right
  end
  device:play( ao.array2string(buffer) )

This replaces the not-very-elegant piece of lua code involving not-very-portable bit operations
to put together an table of bytes then concat the table into the byte-string,
and which also runs nearly four times slower than array2string :

  local buf_size = format.bits/8 * format.channels * format.rate
  local buffer = {}
  for i = 0,format.rate do    -- one second
    local sample = math.floor((0.75 * 32768
      * math.sin(2 * math.pi * freq * i/format.rate)) + 0.5)
    local lsb = bit.band(sample, 0xff)
    local msb = bit.band(bit.rshift(sample, 8), 0xff)
    buffer[4*i+1] = string.char(lsb)   --  left lsb
    buffer[4*i+2] = string.char(msb)   --  left msb
    buffer[4*i+3] = string.char(lsb)   -- right lsb
    buffer[4*i+4] = string.char(msb)   -- right msb
  end
  local buf_str = table.concat(buffer)
  device:play(buf_str, buf_size)

developed by Linus Sjögren, daurnimator and peterbillam

thelinx@unreliablepollution.net


back to index

this project at GitHub