36 lines
815 B
Elixir
36 lines
815 B
Elixir
defmodule AudioBuffer do
|
|
use GenServer
|
|
|
|
def start_link(_opts) do
|
|
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
|
|
end
|
|
|
|
def append(ref, chunk) do
|
|
GenServer.cast(__MODULE__, {:append, ref, chunk})
|
|
end
|
|
|
|
def get_and_clear(ref) do
|
|
GenServer.call(__MODULE__, {:get_and_clear, ref})
|
|
end
|
|
|
|
def flush_all() do
|
|
GenServer.call(__MODULE__, :flush_all)
|
|
end
|
|
|
|
def init(state), do: {:ok, state}
|
|
|
|
def handle_cast({:append, ref, chunk}, state) do
|
|
updated = Map.update(state, ref, [chunk], fn chunks -> chunks ++ [chunk] end)
|
|
{:noreply, updated}
|
|
end
|
|
|
|
def handle_call({:get_and_clear, ref}, _from, state) do
|
|
{chunks, new_state} = Map.pop(state, ref, [])
|
|
{:reply, chunks, new_state}
|
|
end
|
|
|
|
def handle_call(:flush_all, _from, state) do
|
|
{:reply, state, %{}}
|
|
end
|
|
end
|