From 7d7fd7134131cb11149505ff8c02a72eb7332c8b Mon Sep 17 00:00:00 2001 From: Howard Mao Date: Wed, 8 Jan 2014 18:25:55 -0500 Subject: [PATCH] add a FileInput AudioNode type --- src/sndfile.jl | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/src/sndfile.jl b/src/sndfile.jl index d81f8bb..70183aa 100644 --- a/src/sndfile.jl +++ b/src/sndfile.jl @@ -1,4 +1,4 @@ -export openAudio, closeAudio, readFrames +export openAudio, closeAudio, readFrames, FileInput const sndfile = "libsndfile" @@ -49,9 +49,9 @@ end function readFrames(file::Sndfile, nframes::Integer, dtype::Type = Int16) arr = [] if file.sfinfo.channels == 2 - arr = Array(dtype, 2, nframes) + arr = zeros(dtype, 2, nframes) else - arr = Array(dtype, nframes) + arr = zeros(dtype, nframes) end if dtype == Int16 @@ -73,12 +73,36 @@ function readFrames(file::Sndfile, nframes::Integer, dtype::Type = Int16) end if nread == 0 - return [] + return Nothing end - if file.sfinfo.channels == 2 - return arr[:, 1:nread] - end - - return arr[1:nread] + return arr +end + +type FileInput <: AudioNode + active::Bool + file::Sndfile + + function FileInput(path::String) + node = new(false, openAudio(path)) + finalizer(node, node -> closeAudio(node.file)) + return node + end +end + +function render(node::FileInput, device_input::AudioBuf, info::DeviceInfo) + @assert node.file.sfinfo.samplerate == info.sample_rate + + audio = readFrames(node.file, info.buf_size, AudioSample) + + if audio == Nothing + return zeros(AudioSample, info.buf_size), false + end + + # if the file is stereo, mix the two channels together + if node.file.sfinfo.channels == 2 + return (audio[1, :] / 2) + (audio[2, :] / 2), node.active + end + + return audio, node.active end