diff --git a/README.md b/README.md index 0c276ee..467beef 100644 --- a/README.md +++ b/README.md @@ -53,13 +53,26 @@ PortAudio.jl also provides convenience wrappers around the `PortAudioStream` typ ```julia stream = PortAudioStream(2, 2) -write(stream, stream) +try + # cancel with Ctrl-C + write(stream, stream) +finally + close(stream) +end +``` + +### Use `do` syntax to auto-close the stream +```julia +PortAudioStream(2, 2) do stream + write(stream, stream) +end ``` ### Open your built-in microphone and speaker by name ```julia -stream = PortAudioStream("Built-in Microph", "Built-in Output") -write(stream, stream) +PortAudioStream("Built-in Microph", "Built-in Output") do stream + write(stream, stream) +end ``` ### Record 10 seconds of audio and save to an ogg file @@ -79,6 +92,8 @@ julia> buf = read(stream, 10s) ▁▄▂▃▅▃▂▄▃▂▂▁▁▂▂▁▁▄▃▁▁▄▂▁▁▁▄▃▁▁▃▃▁▁▁▁▁▁▁▁▄▄▄▄▄▂▂▂▁▃▃▁▃▄▂▁▁▁▁▃▃▂▁▁▁▁▁▁▃▃▂▂▁▃▃▃▁▁▁▁ ▁▄▂▃▅▃▂▄▃▂▂▁▁▂▂▁▁▄▃▁▁▄▂▁▁▁▄▃▁▁▃▃▁▁▁▁▁▁▁▁▄▄▄▄▄▂▂▂▁▃▃▁▃▄▂▁▁▁▁▃▃▂▁▁▁▁▁▁▃▃▂▂▁▃▃▃▁▁▁▁ +julia> close(stream) + julia> save(joinpath(homedir(), "Desktop", "myvoice.ogg"), buf) ``` diff --git a/src/PortAudio.jl b/src/PortAudio.jl index a3c5665..be769b0 100644 --- a/src/PortAudio.jl +++ b/src/PortAudio.jl @@ -210,6 +210,16 @@ function PortAudioStream(inchans=2, outchans=2; kwargs...) PortAudioStream(indevice, outdevice, inchans, outchans; kwargs...) end +# handle do-syntax +function PortAudioStream(fn::Function, args...; kwargs...) + str = PortAudioStream(args...; kwargs...) + try + fn(str) + finally + close(str) + end +end + const pa_inited = Ref(false) const active_streams = Set{PortAudioStream}()