|
| 1 | +const canvasElement = document.getElementById('canvas') |
| 2 | +const canvasContext = canvasElement.getContext('2d') |
| 3 | +const WIDTH = canvasElement.width = window.innerWidth |
| 4 | +const HEIGHT = canvasElement.height = 512 |
| 5 | + |
| 6 | +let audioCtx = new AudioContext() |
| 7 | +let analyser = audioCtx.createAnalyser() |
| 8 | +analyser.smoothingTimeConstant = 0.0 |
| 9 | +analyser.fftSize = 1024 |
| 10 | + |
| 11 | +let bufferLength = analyser.frequencyBinCount |
| 12 | +let eightBufferLength = 8 * bufferLength |
| 13 | +let dataArray = new Uint8Array(bufferLength) |
| 14 | + |
| 15 | +let imageDataFrame = canvasContext.createImageData(2, canvasElement.height) |
| 16 | +for (let i = 0; i < imageDataFrame.data.length * 4; i += 8) { |
| 17 | + for(let j = 3; j <= 7; j++) { |
| 18 | + imageDataFrame.data[i + j] = 255 // = 0,0,0,255|255,255,255,255 |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +function getData() { |
| 23 | + let request = new XMLHttpRequest() |
| 24 | + request.open('GET', rootPath, true) |
| 25 | + request.responseType = 'arraybuffer' |
| 26 | + |
| 27 | + request.onload = () => { |
| 28 | + var audioData = request.response |
| 29 | + |
| 30 | + audioCtx.decodeAudioData(audioData, buffer => { |
| 31 | + |
| 32 | + let offlineCtx = new OfflineAudioContext(2, buffer.length, 44100) |
| 33 | + let source = offlineCtx.createBufferSource() |
| 34 | + source.buffer = buffer |
| 35 | + |
| 36 | + source.connect(offlineCtx.destination) |
| 37 | + source.start() |
| 38 | + |
| 39 | + offlineCtx |
| 40 | + .startRendering() |
| 41 | + .then(renderedBuffer => { |
| 42 | + const song = audioCtx.createBufferSource() |
| 43 | + song.buffer = renderedBuffer |
| 44 | + |
| 45 | + song.connect(audioCtx.destination) |
| 46 | + song.connect(analyser) |
| 47 | + // // play.onclick = function() { |
| 48 | + // song.playbackRate.value = 2 |
| 49 | + song.start() |
| 50 | + // } |
| 51 | + song.onended = function(e) { |
| 52 | + console.log('finished') |
| 53 | + } |
| 54 | + analyser.getByteFrequencyData(dataArray) |
| 55 | + draw() |
| 56 | + }) |
| 57 | + .catch(err => { |
| 58 | + console.log('Rendering failed: ' + err) |
| 59 | + // Note: The promise should reject when startRendering is called a second time on an OfflineAudioContext |
| 60 | + }) |
| 61 | + }) |
| 62 | + } |
| 63 | + request.send() |
| 64 | +} |
| 65 | + |
| 66 | +getData() |
| 67 | + |
| 68 | +let x= 0 |
| 69 | +function draw() { |
| 70 | + requestAnimationFrame(draw) |
| 71 | + analyser.getByteFrequencyData(dataArray) |
| 72 | + for (let i = 0, y = eightBufferLength; i < bufferLength; i++, y -= 8) { |
| 73 | + imageDataFrame.data[y] = dataArray[i] |
| 74 | + } |
| 75 | + canvasContext.putImageData(imageDataFrame, x, 0) |
| 76 | + x < WIDTH ? x++ : x = 0 |
| 77 | +} |
0 commit comments