您好:我对音频(歌曲)可视化的实现有疑问:
目前,HTML文件和CSS文件显示我想要的内容(黑色框下方有蓝色/青色框,以及audio.controls
显示),音频播放应该如此。但是,script.js JavaScript文件无法显示正在播放的音频。这是JavaScript文件的 链接 ,我使用 Web Audio API 或其他内容的问题其他?这是我的代码:
HTML - index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<link rel="stylesheet" type="text/css" href="./style.css">
<script type="text/javascript" src="./script.js"></script>
<title>Audio Visualizer</title>
</head>
<body>
<div id="mp3_player">
<div id="audio_box"></div>
<canvas id="analyser_render"></canvas>
</div>
</body>
</html>
CSS style.css
#mp3_player {
width: 500px;
height: 60px;
background: #000;
padding: 5px;
margin: 50px auto;
}
<code>#mp3_player > div > audio{
width: 500px;
background: #000;
float: left;
}
<code>#mp3_player > canvas{
width: 500px;
height: 30px;
background: #002D3C;
float: left;
}
JavaScript script.js
var audio = new Audio();
audio.src = 'gypsyheart.mp3';
audio.controls = true;
audio.loop = true;
audio.autoplay = false;<code>
var canvas, ctx, source, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
window.addEventListener("load", initMp3Player, false);
function initMp3Player(){
document.getElementById('audio_box').appendChild(audio);
context = new AudioContext();
analyser = context.CreateAnalyser();
canvas= document.getElementById('analyser_render');
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(audio);
source.connect(context.destination);
frameLooper();
}
function frameLooper(){
window.requestAnimationFrame(frameLooper);
fbc_array = new Uint8Array(analyser.frequencyBinCount);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#00CCFF';
bars = 100;
for (var i = 0; i < bars; i++) {
bar_x = i*3;
bar_height = -(fbc_array[i] / 2);
bar_width = 2
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
文件树
_folder includes (with no sub-folders):_
gypsyheart.mp3
index.html
style.css
script.js
感谢您帮助我。所有意见和建议表示赞赏。如果你对如何处理(简单地)可视化(简单)音乐的问题有不同的想法,我很乐意听到它,并且愿意接受解决这个问题的不同方法!对此处的任何格式错误表示歉意(第一次使用Stack Overflow)!
-Quin