Last active
June 21, 2024 19:49
-
-
Save mbauman/f50e0fcc20a2a16fd7e9a015f9cc54c1 to your computer and use it in GitHub Desktop.
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
begin | |
# Straightforward adaptation from https://github.com/JuliaPluto/PlutoUI.jl/pull/54 by @mthelm85 | |
struct Microphone end | |
function Base.show(io::IO, ::MIME"text/html", microphone::Microphone) | |
mic_id = String(rand('a':'z', 12)) | |
mic_btn_id = String(rand('a':'z', 12)) | |
PlutoUI.withtag(() -> (), io, :audio, :id => mic_id) | |
print(io, """<input type="button" id="$mic_btn_id" class="mic-button" value="Stop">""") | |
PlutoUI.withtag(io, :script) do | |
print(io, """ | |
const player = document.getElementById('$mic_id'); | |
const stop = document.getElementById('$mic_btn_id'); | |
const handleSuccess = function(stream) { | |
const context = new AudioContext({ sampleRate: 16384 }); | |
const analyser = context.createAnalyser(); | |
const source = context.createMediaStreamSource(stream); | |
analyser.fftSize = 32768; | |
source.connect(analyser); | |
const bufferLength = analyser.frequencyBinCount; | |
let dataArray = new Float32Array(bufferLength); | |
let animFrame; | |
const streamAudio = () => { | |
animFrame = requestAnimationFrame(streamAudio); | |
analyser.getFloatTimeDomainData(dataArray); | |
player.value = dataArray; | |
player.dispatchEvent(new CustomEvent("input")); | |
} | |
streamAudio(); | |
stop.onclick = e => { | |
source.disconnect(analyser); | |
cancelAnimationFrame(animFrame); | |
} | |
} | |
navigator.mediaDevices.getUserMedia({ audio: true, video: false }) | |
.then(handleSuccess) | |
""" | |
) | |
end | |
PlutoUI.withtag(io, :style) do | |
print(io, """ | |
.mic-button { | |
background-color: darkred; | |
border: none; | |
border-radius: 6px; | |
color: white; | |
padding: 15px 32px; | |
text-align: center; | |
text-decoration: none; | |
display: inline-block; | |
font-size: 16px; | |
font-family: "Alegreya Sans", sans-serif; | |
margin: 4px 2px; | |
cursor: pointer; | |
} | |
""" | |
) | |
end | |
end | |
PlutoUI.get(microphone::Microphone) = microphone | |
md"### magic from [this snippet](https://gist.github.com/mbauman/f50e0fcc20a2a16fd7e9a015f9cc54c1)" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment