|
| 1 | +window.onload = () => { |
| 2 | + checkHref(location.href); |
| 3 | +}; |
| 4 | + |
| 5 | +function checkHref(href) { |
| 6 | + const streamId = new URL(href).searchParams.get("streamId"); |
| 7 | + if (streamId) { |
| 8 | + start(streamId); |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +function start(streamId) { |
| 13 | + navigator.webkitGetUserMedia( |
| 14 | + { |
| 15 | + audio: { |
| 16 | + mandatory: { |
| 17 | + chromeMediaSource: "tab", // The media source must be 'tab' here. |
| 18 | + chromeMediaSourceId: streamId, |
| 19 | + }, |
| 20 | + }, |
| 21 | + video: false, |
| 22 | + }, |
| 23 | + function (stream) { |
| 24 | + draw(stream); |
| 25 | + }, |
| 26 | + function (error) { |
| 27 | + console.error(error); |
| 28 | + } |
| 29 | + ); |
| 30 | +} |
| 31 | + |
| 32 | +function draw(stream) { |
| 33 | + // at this point the sound of the tab becomes muted with no way to unmute it |
| 34 | + const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); |
| 35 | + const source = audioCtx.createMediaStreamSource(stream); |
| 36 | + const analyser = audioCtx.createAnalyser(); |
| 37 | + analyser.fftSize = 2048; |
| 38 | + const bufferLength = analyser.frequencyBinCount; |
| 39 | + const dataArray = new Uint8Array(bufferLength); |
| 40 | + source.connect(analyser); |
| 41 | + analyser.connect(audioCtx.destination); |
| 42 | + |
| 43 | + const canvas = document.createElement("canvas"); |
| 44 | + canvas.width = 800; |
| 45 | + canvas.height = 200; |
| 46 | + canvas.style.cssText = |
| 47 | + "position: fixed; top: 0; left: 0; z-index: 2147483647; background: #333a;"; |
| 48 | + document.body.appendChild(canvas); |
| 49 | + const canvasCtx = canvas.getContext("2d"); |
| 50 | + |
| 51 | + function draw() { |
| 52 | + analyser.getByteFrequencyData(dataArray); |
| 53 | + canvasCtx.clearRect(0, 0, canvas.width, canvas.height); |
| 54 | + canvasCtx.beginPath(); |
| 55 | + const barWidth = ~~(bufferLength / canvas.width); |
| 56 | + for (let x = 0; x < canvas.width; x++) { |
| 57 | + let i = x * barWidth; |
| 58 | + let item = dataArray[i]; |
| 59 | + const barHeight = map(item, 0, 255, 0, canvas.height); |
| 60 | + canvasCtx.lineTo(x, canvas.height - barHeight); |
| 61 | + } |
| 62 | + canvasCtx.strokeStyle = "rgba(255, 255, 255, 0.9)"; |
| 63 | + canvasCtx.stroke(); |
| 64 | + requestAnimationFrame(draw); |
| 65 | + } |
| 66 | + |
| 67 | + function map(x, in_min, in_max, out_min, out_max) { |
| 68 | + return ((x - in_min) * (out_max - out_min)) / (in_max - in_min) + out_min; |
| 69 | + } |
| 70 | + |
| 71 | + requestAnimationFrame(draw); |
| 72 | +} |
0 commit comments