Skip to content

Instantly share code, notes, and snippets.

@elihugarret
Last active October 9, 2020 16:37
Show Gist options
  • Save elihugarret/d9dfa4590a0a718a998cfb24554b6fe4 to your computer and use it in GitHub Desktop.
Save elihugarret/d9dfa4590a0a718a998cfb24554b6fe4 to your computer and use it in GitHub Desktop.
Simple Pluto.jl notebook that plots audio input.
### A Pluto.jl notebook ###
# v0.11.8
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
el
end
end
# ╔═╡ d7641af0-e514-11ea-159d-4b0ea0294203
using Plots, SampledSignals
# ╔═╡ 57b70420-e514-11ea-1a37-11efa5f2726c
@bind audio HTML("""
<audio id="player"></audio>
<button class="button" id="stopButton">Stop</button>
<script>
const player = document.getElementById('player');
const stop = document.getElementById('stopButton');
const handleSuccess = function(stream) {
const context = new AudioContext({ sampleRate: 44100 });
const analyser = context.createAnalyser();
const source = context.createMediaStreamSource(stream);
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)
</script>
<style>
.button {
background-color: darkred;
border: none;
border-radius: 12px;
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;
}
</style>
""")
# ╔═╡ dca970a2-e514-11ea-2975-0be3321223c8
plot(domain(SampleBuf(Array(audio), 44100)), SampleBuf(Array(audio), 44100), legend=false, ylims=(-1,1))
# ╔═╡ 61611e10-e515-11ea-23b6-13038ba00d7a
# ╔═╡ Cell order:
# ╠═57b70420-e514-11ea-1a37-11efa5f2726c
# ╠═d7641af0-e514-11ea-159d-4b0ea0294203
# ╠═dca970a2-e514-11ea-2975-0be3321223c8
# ╠═61611e10-e515-11ea-23b6-13038ba00d7a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment