Created
December 16, 2014 22:18
-
-
Save LPGhatguy/2572e27dd1cca704a029 to your computer and use it in GitHub Desktop.
Demonstration of encoding SoundData into a packet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ffi = require("ffi") | |
-- Create a C struct representing the header for our packet | |
ffi.cdef([[ | |
typedef struct { | |
uint32_t uuid; // user identifier | |
uint32_t size; // in bytes | |
uint32_t bitrate; // in Hz | |
uint16_t bitdepth; // bits per sample | |
uint16_t channels; // probably 1 or 2 | |
} VoipHeader; | |
]]) | |
local VoipHeader = ffi.typeof("VoipHeader") | |
local pVoipHeader = ffi.typeof("VoipHeader*") | |
-- Create a SoundData object to try to transmit | |
local mySoundData = love.sound.newSoundData(8, 44100, 8, 1) | |
mySoundData:setSample(0, 0.5) | |
mySoundData:setSample(7, 0.5) | |
-- Create a header for this specific SoundData | |
local packet = ffi.new(VoipHeader, { | |
uuid = 1, -- dud UUID, first user | |
size = 8, -- 8 bytes of data | |
bitrate = 44100, -- 44100 Hz, like we specified above | |
channels = 1, -- 1 channel | |
bitdepth = 8 -- 8-bit audio | |
}) | |
-- Encodes a C struct as a string | |
local function encode(data) | |
return ffi.string(ffi.cast("const char*", data), ffi.sizeof(data)) | |
end | |
-- Turns a string back into a C struct | |
local function decode(data, pstruct) | |
return ffi.cast(pstruct, data)[0] | |
end | |
-- Encode our header and payload as a string | |
local struct = encode(packet) | |
local encoded = struct .. ffi.string(mySoundData:getPointer(), 8) | |
-- Decode our encoded packet | |
local header = decode(encoded, pVoipHeader) | |
local encodedPayload = encoded:sub(ffi.sizeof(VoipHeader) + 1) | |
local payload = ffi.new("uint8_t[8]", encoded:sub(ffi.sizeof(VoipHeader)+1)) | |
local newSoundData = love.sound.newSoundData(header.size, header.bitrate, header.bitdepth, header.channels) | |
ffi.copy(newSoundData:getPointer(), payload, 8) | |
print(newSoundData:getSample(0)) -- around 0.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment