PortAudio.jl/examples/audiometer.jl

56 lines
1.6 KiB
Julia
Raw Permalink Normal View History

2016-03-20 09:05:21 +01:00
using PortAudio
2021-06-01 19:44:23 +02:00
"""
Continuously read from the default audio input and plot an
ASCII level/peak meter
"""
2016-03-20 09:05:21 +01:00
function micmeter(metersize)
2021-06-01 19:44:23 +02:00
mic = PortAudioStream(1, 0; latency = 0.1)
2016-03-20 09:05:21 +01:00
signalmax = zero(eltype(mic))
println("Press Ctrl-C to quit")
while true
block = read(mic, 512)
blockmax = maximum(abs.(block)) # find the maximum value in the block
2016-03-20 09:05:21 +01:00
signalmax = max(signalmax, blockmax) # keep the maximum value ever
print("\r") # reset the cursor to the beginning of the line
printmeter(metersize, blockmax, signalmax)
end
end
2021-06-01 19:44:23 +02:00
"""
Print an ASCII level meter of the given size. Signal and peak
levels are assumed to be scaled from 0.0-1.0, with peak >= signal
"""
2016-03-20 09:05:21 +01:00
function printmeter(metersize, signal, peak)
# calculate the positions in terms of characters
peakpos = clamp(round(Int, peak * metersize), 0, metersize)
2021-06-01 19:44:23 +02:00
meterchars = clamp(round(Int, signal * metersize), 0, peakpos - 1)
blankchars = max(0, peakpos - meterchars - 1)
2016-03-20 09:05:21 +01:00
for position in 1:meterchars
2021-06-01 19:44:23 +02:00
printstyled(">", color = barcolor(metersize, position))
2016-03-20 09:05:21 +01:00
end
2021-06-01 19:44:23 +02:00
print(" "^blankchars)
printstyled("|", color = barcolor(metersize, peakpos))
print(" "^(metersize - peakpos))
2016-03-20 09:05:21 +01:00
end
2021-06-01 19:44:23 +02:00
"""
Compute the proper color for a given position in the bar graph. The first
2016-03-20 09:05:21 +01:00
half of the bar should be green, then the remainder is yellow except the final
2021-06-01 19:44:23 +02:00
character, which is red.
"""
2016-03-20 09:05:21 +01:00
function barcolor(metersize, position)
2021-06-01 19:44:23 +02:00
if position / metersize <= 0.5
2016-03-20 09:05:21 +01:00
:green
elseif position == metersize
:red
else
:yellow
end
end
micmeter(80)