簡體   English   中英

如何創建JavaScript Audio Visualizer?

[英]How to create a JavaScript Audio Visualizer?

我一直在尋找一些解決方案,但並沒有發現太多。 我想要一些非常簡單的東西,如下圖所示。 有沒有人在項目中使用過一個? 我可以使用任何建議或任何API? 謝謝。

在此處輸入圖片說明

這是基礎:

  • 你需要一塊畫布
  • 您需要畫布上下文
  • 您需要音頻上下文

 var canvas = document.createElement("canvas"); canvas.width = 500; canvas.height = 180; var ctx = canvas.getContext("2d"); ctx.fillStyle = "black"; ctx.strokeStyle = "white"; ctx.lineCap = "round"; var auctx; window.onload = () => { document.body.appendChild(canvas); auctx = new(window.AudioContext || window.webkitAudioContext)(); startAudio(); } var buffer, src, analyser, buffLen; var barWidth, dataArray; function startAudio() { var url = "https://cf-media.sndcdn.com/cTGZiRbnSouE.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20vY1RHWmlSYm5Tb3VFLjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE1MTk5NTQ5NjB9fX1dfQ__&Signature=JmNkAHzih0~f3lQVwvPXFeTIUVuMXbwlbqizsXbCtc6lFIxjRlqa3wUGp5-xAkt7AUlhiYxu~Wscc6MfQTTc527DHJURMpdqvdXv61ll-WJqoV1V-tpWSa~qR-NEAWGCGBvrge0BkRRAsOHFljeLNCvO3DjzH7lSTPMlV-MtbFV2k-PiY0vrY1LuicAOcfEtXYTiMBkg-rhzkeHFcNHYt2Nb2hmIvmWFI1cFG74FBIXTnVPAg2Yo0r-LeiirWvSgewkIu~zPzaVYjnPaN1y-ZGnPBFiBSC1mpVhtB5wkhTXF5LFthkGUHnUK2ybESr-1uOH9GLye-7dxdIXx~A1LDA__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ"; // nice url var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = function() { auctx.decodeAudioData(request.response, function(buffer) { buffer = buffer; src = auctx.createBufferSource(); src.buffer = buffer; src.loop = false; src.connect(auctx.destination); src.start(0); analyser = auctx.createAnalyser(); src.connect(analyser); analyser.connect(auctx.destination); analyser.fftSize = 256; buffLen = analyser.frequencyBinCount; dataArray = new Uint8Array(buffLen); barWidth = (500 - 2 * buffLen - 4) / buffLen * 2.5; ctx.lineWidth = barWidth; draw(); }); } request.send(); } function draw() { ctx.fillRect(0, 0, 500, 180); analyser.getByteFrequencyData(dataArray); for (var i = 0; i < buffLen; i++) { ctx.beginPath(); ctx.moveTo(4 + 2 * i * barWidth + barWidth / 2, 178 - barWidth / 2); ctx.lineTo(4 + 2 * i * barWidth + barWidth / 2, 178 - dataArray[i] * 0.65 - barWidth / 2); ctx.stroke(); } requestAnimationFrame(draw); } 
 canvas { background: black; } 

此代碼應該起作用。 您可以添加一些圖像和調整設置。

我認為這可能就是您要尋找的。 對不起,我來晚了。

 // AUDIO CONTEXT window.AudioContext = (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext); if (!AudioContext) alert('This site cannot be run in your Browser. Try a recent Chrome or Firefox. '); var audioContext = new AudioContext(); var currentBuffer = null; // CANVAS var canvasWidth = window.innerWidth, canvasHeight = 120 ; var newCanvas = createCanvas (canvasWidth, canvasHeight); var context = null; window.onload = appendCanvas; function appendCanvas() { document.body.appendChild(newCanvas); context = newCanvas.getContext('2d'); } // the function that loads the sound file //NOTE this program for some reason won't load sound files from like a weebly website so you'll have to add the files to your github or whatever and use that raw audio file function loadMusic(url) { var req = new XMLHttpRequest(); req.open( "GET", url, true ); req.responseType = "arraybuffer"; req.onreadystatechange = function (e) { if (req.readyState == 4) { if(req.status == 200) audioContext.decodeAudioData(req.response, function(buffer) { currentBuffer = buffer; displayBuffer(buffer); }, onDecodeError); else alert('error during the load.Wrong url or cross origin issue'); } } ; req.send(); } function onDecodeError() { alert('error while decoding your file.'); } // MUSIC DISPLAY function displayBuffer(buff /* is an AudioBuffer */) { var drawLines = 500; var leftChannel = buff.getChannelData(0); // Float32Array describing left channel var lineOpacity = canvasWidth / leftChannel.length ; context.save(); context.fillStyle = '#080808' ; context.fillRect(0,0,canvasWidth,canvasHeight ); context.strokeStyle = '#46a0ba'; context.globalCompositeOperation = 'lighter'; context.translate(0,canvasHeight / 2); //context.globalAlpha = 0.6 ; // lineOpacity ; context.lineWidth=1; var totallength = leftChannel.length; var eachBlock = Math.floor(totallength / drawLines); var lineGap = (canvasWidth/drawLines); context.beginPath(); for(var i=0;i<=drawLines;i++){ var audioBuffKey = Math.floor(eachBlock * i); var x = i*lineGap; var y = leftChannel[audioBuffKey] * canvasHeight / 2; context.moveTo( x, y ); context.lineTo( x, (y*-1) ); } context.stroke(); context.restore(); } // Creates the Canvas function createCanvas ( w, h ) { var newCanvas = document.createElement('canvas'); newCanvas.width = w; newCanvas.height = h; return newCanvas; }; // The program runs the url you put into the line below loadMusic('||YOUR LINK||'); 

快樂編碼!

如果您偶然有一個更好的解決方案,可以將代碼發送給我,因為我對此也有些麻煩。 我試圖在不使用外部庫的情況下創建類似soundcloud的聲音。

編輯1

所以我認為,如果我舉一個實際的例子,那就太好了,在這里->

 // AUDIO CONTEXT window.AudioContext = (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext); if (!AudioContext) alert('This site cannot be run in your Browser. Try a recent Chrome or Firefox. '); var audioContext = new AudioContext(); var currentBuffer = null; // CANVAS var canvasWidth = window.innerWidth, canvasHeight = 120 ; var newCanvas = createCanvas (canvasWidth, canvasHeight); var context = null; window.onload = appendCanvas; function appendCanvas() { document.body.appendChild(newCanvas); context = newCanvas.getContext('2d'); } // the function that loads the sound file //NOTE this program for some reason won't load sound files from like a weebly website so you'll have to add the files to your github or whatever and use that raw audio file function loadMusic(url) { var req = new XMLHttpRequest(); req.open( "GET", url, true ); req.responseType = "arraybuffer"; req.onreadystatechange = function (e) { if (req.readyState == 4) { if(req.status == 200) audioContext.decodeAudioData(req.response, function(buffer) { currentBuffer = buffer; displayBuffer(buffer); }, onDecodeError); else alert('error during the load.Wrong url or cross origin issue'); } } ; req.send(); } function onDecodeError() { alert('error while decoding your file.'); } // MUSIC DISPLAY function displayBuffer(buff /* is an AudioBuffer */) { var drawLines = 500; var leftChannel = buff.getChannelData(0); // Float32Array describing left channel var lineOpacity = canvasWidth / leftChannel.length ; context.save(); context.fillStyle = '#080808' ; context.fillRect(0,0,canvasWidth,canvasHeight ); context.strokeStyle = '#46a0ba'; context.globalCompositeOperation = 'lighter'; context.translate(0,canvasHeight / 2); //context.globalAlpha = 0.6 ; // lineOpacity ; context.lineWidth=1; var totallength = leftChannel.length; var eachBlock = Math.floor(totallength / drawLines); var lineGap = (canvasWidth/drawLines); context.beginPath(); for(var i=0;i<=drawLines;i++){ var audioBuffKey = Math.floor(eachBlock * i); var x = i*lineGap; var y = leftChannel[audioBuffKey] * canvasHeight / 2; context.moveTo( x, y ); context.lineTo( x, (y*-1) ); } context.stroke(); context.restore(); } // Creates the Canvas function createCanvas ( w, h ) { var newCanvas = document.createElement('canvas'); newCanvas.width = w; newCanvas.height = h; return newCanvas; }; // The program runs the url you put into the line below loadMusic('https://raw.githubusercontent.com/lightning417techa/Music/master/images/lil%20dicky%20-%20freaky%20friday%20(lyrics)%20ft.%20chris%20brown.mp3'); 
注意:這是此文件所需的文件,有時很煩人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM