在 html 中播放 wav 音频文件的移动波形

Play a moving waveform for wav audio file in html(在 html 中播放 wav 音频文件的移动波形)

本文介绍了在 html 中播放 wav 音频文件的移动波形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 HTML 中为音频文件/标签创建移动波形?单击播放按钮时,必须播放音频 HTML 元素并生成相应的移动波形......如何实现?

<html><头><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/><title id='title'>HTML 页面设置教程</title><script src='riffwave.js'></script><脚本类型="文本/javascript">函数 myFunction(){变量数据 = [];//只是一个数组for (var i=0; i<10000; i++) 数据[i] =/*Math.round(255 * Math.random())*/i;//用随机样本填充数据var wave = new RIFFWAVE(data);//创建波形文件var audio = new Audio(wave.dataURI);//创建 HTML5 音频元素音频.play();}</脚本></头><身体><button type="button" onclick="myFunction()">点击我!</button></身体></html>

我想创建这样的波形

解决方案

和下面一样,但是用canvasjs:

演示:http://seapip.com/canvas/visualizer4/

<代码>/*速度必须更大然后刷新!!!*///从右到左移动的速度,也是x轴上可见的时间量(以毫秒为单位)var 速度 = 10000;//重绘图表的时间,以毫秒为单位var 刷新 = 30;//不带var使其成为html onclick属性可访问的全局变量audioElement = document.getElementById('audioElement');var audioCtx = new (window.AudioContext || window.webkitAudioContext)();var audioSrc = audioCtx.createMediaElementSource(audioElement);var 分析器 = audioCtx.createAnalyser();//将我们的分析器绑定到媒体元素源.audioSrc.connect(分析器);audioSrc.connect(audioCtx.destination);//获取频率数据var frequencyData = new Uint8Array(analyzer.frequencyBinCount);//动画参考var 动画;//创建图表var dps = [];//数据点var chart = new CanvasJS.Chart("chart", {交互启用:假,宽度:500,身高:200,轴X:{标题:时间",valueFormatString: "mm:ss"},Y轴:{标题:分贝"},数据: [{类型:线",数据点:dps}]});图表.render();//播放中audioElement.onplay = function() {//开始绘制动画 = setInterval(function() {画波();}, 刷新);};//暂停时audioElement.onpause = function() {//停止绘制清除间隔(动画);};//结束时audioElement.onended = 函数() {//停止绘制清除间隔(动画);//重置时间时间=0;//重置数据点dps = [];//防止音频循环播放(如果你想让它循环播放,你可以删除它)audioElement.pause();};//最大分贝var max = analyzer.maxDecibels;//最小分贝var min = analyzer.minDecibels;//时间变量时间 = 0;//我们的绘图方法函数drawWave(){//将频率数据复制到频率数据数组.analyzer.getByteFrequencyData(frequencyData);//frequencyData中所有频率的总响度var 总响度 = 0;for(var i = 0; i < frequencyData.length; i++) {总响度+=频率数据[i];}//频率数据中所有频率的平均响度,范围从0到255var averageLoudness = totalLoudness/frequencyData.length/255;//分贝var 分贝 = min + averageLoudness * Math.abs(min - max);//增加时间时间+=刷新;//添加到图表dps.push({x:新日期(时间),y:分贝});//根据广告刷新速度绘制的最大 x 值如果(dps.length > 速度/刷新){dps.shift();}//绘制新图表图表.render();}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio><div id="图表"></div>

<button onclick="audioElement.play()">播放音频</button><button onclick="audioElement.pause()">暂停音频</button><button onclick="audioElement.volume+=0.1">提高音量</button><button onclick="audioElement.volume-=0.1">降低音量</button></div>

请记住,#chart 是一个 div 而不是画布元素,我花了几分钟才弄清楚为什么图表一开始没有显示:P


<小时>


与下面相同,但从右到左绘制.stepSize 变量设置动画速度和步长的大小,如果你想画更大的步,那么它需要移动得更快,如果你想画更小的步,它需要移动得更慢.

演示:http://seapip.com/canvas/visualizer3

//步长(每20ms像素)变量步长 = 0.5;//不带var使其成为html onclick属性可访问的全局变量audioElement = document.getElementById('audioElement');var audioCtx = new (window.AudioContext || window.webkitAudioContext)();var audioSrc = audioCtx.createMediaElementSource(audioElement);var 分析器 = audioCtx.createAnalyser();//将我们的分析器绑定到媒体元素源.audioSrc.connect(分析器);audioSrc.connect(audioCtx.destination);//获取频率数据(800 = 最大频率)var frequencyData = new Uint8Array(400);//使用下面显示所有频率//var frequencyData = new Uint8Array(analysisr.frequencyBinCount);//创建画布var canvas = document.getElementById("wave");canvas.style.width = "500px";canvas.style.height = "100px";//高dpi的东西canvas.width = parseInt(canvas.style.width) * 2;canvas.height = parseInt(canvas.style.height) * 2;//获取画布上下文var ctx = canvas.getContext("2d");//描边颜色ctx.strokeStyle = "#ffff00";//由于高dpi缩放绘制更粗的线ctx.lineWidth = 2;//存储y值var drawY = [canvas.height];//动画参考var 动画;//播放中audioElement.onplay = function() {//开始绘制动画 = setInterval(function() {画波();}, 20);};//暂停时audioElement.onpause = function() {//停止绘制清除间隔(动画);};//结束时audioElement.onended = 函数() {//停止绘制清除间隔(动画);//清除之前的y值drawY = [canvas.height];//防止音频循环播放(如果你想让它循环播放,你可以删除它)audioElement.pause();};//我们的绘图方法函数drawWave(){//将频率数据复制到频率数据数组.analyzer.getByteFrequencyData(frequencyData);//frequencyData中所有频率的总响度var 总响度 = 0;for(var i = 0; i < frequencyData.length; i++) {总响度+=频率数据[i];}//frequencyData中所有频率的平均响度var averageLoudness = totalLoudness/frequencyData.length;//平均响度范围从(0到1),频率响度范围是(0到255)var y = 平均响度/255;//乘以画布高度以获得从(0到画布高度)的比例y *= canvas.height;//由于画布的y轴与正常的y轴相反,我们必须翻转它以获得正常的y轴值y = canvas.height - y;//存储新的y值drawY.push(y);//清除上一张图ctx.clearRect(0, 0, canvas.width, canvas.height);//画线for(var i = drawY.length; i > 0; i--) {//计算x值var x1 = canvas.width - (drawY.length - i - 1) * stepSize;var x2 = canvas.width - (drawY.length - i) * stepSize;//如果x值在画布之外,则停止绘制y值如果(!x2){休息;}ctx.beginPath();ctx.moveTo(x1, drawY[i - 1]);ctx.lineTo(x2, drawY[i]);ctx.stroke();}}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio><canvas id="wave"></canvas>

<button onclick="audioElement.play()">播放音频</button><button onclick="audioElement.pause()">暂停音频</button><button onclick="audioElement.volume+=0.1">提高音量</button><button onclick="audioElement.volume-=0.1">降低音量</button></div>


<小时>


这就是我认为您可能想要的,x 轴是时间,y 轴是所有频率的平均响度.请记住,chrome 等浏览器无法在后台选项卡中正确绘制图形,因为它会限制刷新间隔和音频分析器输出.

演示:http://seapip.com/canvas/visualizer2

//不带var使其成为html onclick属性可访问的全局变量audioElement = document.getElementById('audioElement');var audioCtx = new (window.AudioContext || window.webkitAudioContext)();var audioSrc = audioCtx.createMediaElementSource(audioElement);var 分析器 = audioCtx.createAnalyser();//将我们的分析器绑定到媒体元素源.audioSrc.connect(分析器);audioSrc.connect(audioCtx.destination);//获取频率数据(800 = 最大频率)var frequencyData = new Uint8Array(400);//使用下面显示所有频率//var frequencyData = new Uint8Array(analysisr.frequencyBinCount);//创建画布var canvas = document.getElementById("wave");canvas.style.width = "1000px";canvas.style.height = "100px";//高dpi的东西canvas.width = parseInt(canvas.style.width) * 2;canvas.height = parseInt(canvas.style.height) * 2;//获取画布上下文var ctx = canvas.getContext("2d");//设置描边颜色为黄色ctx.strokeStyle = "#ffff00";//由于高 dpi 缩放,绘制两倍粗的线ctx.lineWidth = 2;//保存上一张图中的x和yvar drawX = 0;var drawY = 0;//总时长(秒)var 持续时间;//动画参考var 动画;//音频已加载audioElement.oncanplaythrough = function() {//获取持续时间持续时间 = audioElement.duration;//播放中audioElement.onplay = function() {//开始绘制画波();};//暂停时audioElement.onpause = function() {//停止绘制取消动画帧(动画);};//结束时audioElement.onended = 函数() {//停止绘制取消动画帧(动画);//清除上一张图ctx.clearRect(0, 0, canvas.width, canvas.height);//清除之前的x和y值绘制X = 0;绘制Y = 0;//防止音频循环播放(如果你想让它循环播放,你可以删除它)audioElement.pause();};};//我们的绘图方法函数drawWave(){//当前时间(秒)var currentTime = audioElement.currentTime;//将频率数据复制到频率数据数组.analyzer.getByteFrequencyData(frequencyData);//frequencyData中所有频率的总响度var 总响度 = 0;for(var i = 0; i < frequencyData.length; i++) {总响度+=频率数据[i];}//frequencyData中所有频率的平均响度var averageLoudness = totalLoudness/frequencyData.length;//获取前一个x轴值var previousDrawX = drawX;//歌曲进度比例(从0到1)drawX = 当前时间/持续时间;//乘以画布宽度得到x轴值drawX *= canvas.width;//获取上一个y轴值var previousDrawY = drawY;//平均响度范围从(0到1),频率响度范围是(0到255)drawY = 平均响度/255;//乘以画布高度以获得从(0到画布高度)的比例drawY *= canvas.height;//由于画布的y轴与正常的y轴相反,我们必须翻转它以获得正常的y轴值drawY = canvas.height - drawY;//画线ctx.beginPath();ctx.moveTo(previousDrawX, previousDrawY);ctx.lineTo(drawX, drawY);ctx.stroke();//动画动画 = requestAnimationFrame(drawWave);}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio><canvas id="wave"></canvas>

<button onclick="audioElement.play()">播放音频</button><button onclick="audioElement.pause()">暂停音频</button><button onclick="audioElement.volume+=0.1">提高音量</button><button onclick="audioElement.volume-=0.1">降低音量</button></div>


<小时>


画布可视化示例

演示:http://seapip.com/canvas/visualizer/

//不带var使其成为html onclick属性可访问的全局变量audioElement = document.getElementById('audioElement');var audioCtx = new (window.AudioContext || window.webkitAudioContext)();var audioSrc = audioCtx.createMediaElementSource(audioElement);var 分析器 = audioCtx.createAnalyser();//将我们的分析器绑定到媒体元素源.audioSrc.connect(分析器);audioSrc.connect(audioCtx.destination);//获取频率数据(400 = 最大频率)var frequencyData = new Uint8Array(400);//使用下面显示所有频率//var frequencyData = new Uint8Array(analysisr.frequencyBinCount);//创建画布var canvas = document.getElementById("wave");canvas.style.width = "500px";canvas.style.height = "100px";//高dpi的东西canvas.width = parseInt(canvas.style.width) * 2;canvas.height = parseInt(canvas.style.height) * 2;//获取画布上下文var ctx = canvas.getContext("2d");//设置描边颜色ctx.strokeStyle = "#ffff00"//由于高 dpi 缩放,绘制两倍粗的线ctx.lineWidth = 2;//动画参考var 动画;//播放中audioElement.onplay = 功能() {画波();};//暂停时audioElement.onpause = 功能() {取消动画帧(动画);};//结束时audioElement.onended = 功能() {取消动画帧(动画);};//我们的绘图方法函数drawWave(){//将频率数据复制到频率数据数组.analyzer.getByteFrequencyData(frequencyData);//画波浪ctx.clearRect(0, 0, canvas.width, canvas.height);for(var i = 1; i < frequencyData.length; i++) {var x1 = canvas.width/(frequencyData.length - 1) * (i - 1);var x2 = canvas.width/(frequencyData.length - 1) * i;var y1 = canvas.height - frequencyData[i - 1]/255 * canvas.height;var y2 = canvas.height - frequencyData[i]/255 * canvas.height;if(x1 && y1 && x2 && y2) {ctx.beginPath();ctx.moveTo(x1, y1);ctx.lineTo(x2, y2);ctx.stroke();}}//动画动画 = requestAnimationFrame(drawWave);}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio><canvas id="wave"></canvas>

<button onclick="document.getElementById('audioElement').play()">播放音频</button><button onclick="document.getElementById('audioElement').pause()">暂停音频</button><button onclick="document.getElementById('audioElement').volume+=0.1">提高音量</button><button onclick="document.getElementById('audioElement').volume-=0.1">降低音量</button></div>


<小时>


关于音频可视化的插件和教程:

https://wavesurfer-js.org/

http://waveformjs.org/#weird

https://www.bignerdranch.com/blog/music-visualization-with-d3-js/

https://github.com/wayou/HTML5_Audio_Visualizer

https://www.patrick-wied.at/blog/how-to-create-audio-visualizations-with-javascript-html

https://p5js.org/examples/examples/Sound_Frequency_Spectrum.php

How to create a moving waveform for a audio file/tag in HTML? When play button is clicked,the audio HTML element must be played and a corresponding moving waveform for the same should be generated....how to implement this?

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title id='title'>HTML Page setup Tutorial</title> 
        <script src='riffwave.js'></script>

        <script type="text/javascript">

    function myFunction()
    {
    var data = []; // just an array
for (var i=0; i<10000; i++) data[i] = /*Math.round(255 * Math.random())*/i; // fill data with random samples
var wave = new RIFFWAVE(data); // create the wave file
var audio = new Audio(wave.dataURI); // create the HTML5 audio element
audio.play();


    }
    </script>
    </head>
<body>

<button type="button" onclick="myFunction()">Click Me!</button>
</body>
</html>

I want to create a waveform like this

解决方案

Same as below but then with canvasjs:

Demo: http://seapip.com/canvas/visualizer4/

/*
Speed has to be bigger then refresh!!!
*/

//Speed to move from right to left, also the visible amount of time on the x axis (in milliseconds)
var speed = 10000;

//Time in milliseconds to redraw chart
var refresh = 30;

//Without var to make it a global variable accessable by the html onclick attribute 
audioElement = document.getElementById('audioElement');
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audioSrc = audioCtx.createMediaElementSource(audioElement);
var analyser = audioCtx.createAnalyser();

// Bind our analyser to the media element source.
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);

//Get frequency data
var frequencyData = new Uint8Array(analyser.frequencyBinCount);

//The animation reference
var animation;

//Create chart
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chart", {
    interactivityEnabled: false,
    width: 500,
    height: 200,
    axisX: {
        title: "Time",
        valueFormatString: "mm:ss"
    },
    axisY: {
        title: "dB"
    },
    data: [{
        type: "line",
        dataPoints: dps
    }]
});
chart.render();

//On play
audioElement.onplay = function() {
    //Start drawing
    animation = setInterval(function() {
        drawWave();
    }, refresh);
};

//On pause
audioElement.onpause = function() {
    //Stop drawing
    clearInterval(animation);
};

//On ended
audioElement.onended = function() {
    //Stop drawing
    clearInterval(animation);

    //Reset time
    time = 0;

    //Reset dataPoints
    dps = [];

    //Prevent audio from looping (you can remove this if you want it to loop)
    audioElement.pause();
};

//Max dB
var max = analyser.maxDecibels;

//Min dB
var min = analyser.minDecibels;

//Time
var time = 0;

//Our drawing method
function drawWave() {

    // Copy frequency data to frequencyData array.
    analyser.getByteFrequencyData(frequencyData);

    //Total loudness of all frequencies in frequencyData
    var totalLoudness = 0;
    for(var i = 0; i < frequencyData.length; i++) {
        totalLoudness += frequencyData[i];
    }

    //Average loudness of all frequencies in frequencyData on scale from 0 to 255
    var averageLoudness = totalLoudness / frequencyData.length / 255;

    //Decibels
    var decibels = min + averageLoudness * Math.abs(min - max);

    //Increase time
    time += refresh;

    //Add to chart
    dps.push({
        x: new Date(time),
        y: decibels
    });

    //Maximum x values to draw based on speed ad refresh
    if(dps.length > speed / refresh) {
        dps.shift();
    }

    //Draw new chart
    chart.render(); 
}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio>
<div id="chart"></div>
<div>
  <button onclick="audioElement.play()">Play the Audio</button>
  <button onclick="audioElement.pause()">Pause the Audio</button>
  <button onclick="audioElement.volume+=0.1">Increase Volume</button>
  <button onclick="audioElement.volume-=0.1">Decrease Volume</button>
</div>

Keep in mind that #chart is a div instead of a canvas element, it took me a few minutes to find out why the chart wasn't showing at first :P




Same as below but with plotting from right to left. The stepSize variable sets both the animation speed and the size of the steps, if you want bigger steps to be drawn in then it needs to move faster and if you want smaller steps to be drawn it needs to move slower.

Demo: http://seapip.com/canvas/visualizer3

//Step size (pixels per 20ms)
var stepSize = 0.5;

//Without var to make it a global variable accessable by the html onclick attribute 
audioElement = document.getElementById('audioElement');
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audioSrc = audioCtx.createMediaElementSource(audioElement);
var analyser = audioCtx.createAnalyser();

// Bind our analyser to the media element source.
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);

//Get frequency data (800 = max frequency)
var frequencyData = new Uint8Array(400);
//Use below to show all frequencies
//var frequencyData = new Uint8Array(analyser.frequencyBinCount);

//Create canvas
var canvas = document.getElementById("wave");
canvas.style.width = "500px";
canvas.style.height = "100px";

//High dpi stuff
canvas.width = parseInt(canvas.style.width) * 2;
canvas.height = parseInt(canvas.style.height) * 2;

//Get canvas context
var ctx = canvas.getContext("2d");

//Stroke color
ctx.strokeStyle = "#ffff00";

//Draw thicker lines due to high dpi scaling
ctx.lineWidth = 2;

//Store y values
var drawY = [canvas.height];

//The animation reference
var animation;

//On play
audioElement.onplay = function() {
    //Start drawing
    animation = setInterval(function() {
        drawWave();
    }, 20);
};

//On pause
audioElement.onpause = function() {
    //Stop drawing
    clearInterval(animation);
};

//On ended
audioElement.onended = function() {
    //Stop drawing
    clearInterval(animation);

    //Clear previous y values
    drawY = [canvas.height];

    //Prevent audio from looping (you can remove this if you want it to loop)
    audioElement.pause();
};

//Our drawing method
function drawWave() {

    // Copy frequency data to frequencyData array.
    analyser.getByteFrequencyData(frequencyData);

    //Total loudness of all frequencies in frequencyData
    var totalLoudness = 0;
    for(var i = 0; i < frequencyData.length; i++) {
        totalLoudness += frequencyData[i];
    }

    //Average loudness of all frequencies in frequencyData
    var averageLoudness = totalLoudness / frequencyData.length;

    //Scale of average loudness from (0 to 1), frequency loudness scale is (0 to 255)
    var y = averageLoudness / 255;
    //Multiply with canvas height to get scale from (0 to canvas height)
    y *= canvas.height;
    //Since a canvas y axis is inverted from a normal y axis we have to flip it to get a normal y axis value
    y = canvas.height - y;

    //Store new y value
    drawY.push(y);

    //Clear previous drawing
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    //Draw line
    for(var i = drawY.length; i > 0; i--) {

        //calculate x values
        var x1 = canvas.width - (drawY.length - i - 1) * stepSize;
        var x2 = canvas.width - (drawY.length - i) * stepSize;

        //Stop drawing y values if the x value is outside the canvas
        if(!x2) {
            break;
        }
        ctx.beginPath();
        ctx.moveTo(x1, drawY[i - 1]);
        ctx.lineTo(x2, drawY[i]);
        ctx.stroke();
    }
}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio>
<canvas id="wave"></canvas>
<div>
  <button onclick="audioElement.play()">Play the Audio</button>
  <button onclick="audioElement.pause()">Pause the Audio</button>
  <button onclick="audioElement.volume+=0.1">Increase Volume</button>
  <button onclick="audioElement.volume-=0.1">Decrease Volume</button>
</div>




Here's what I think you probably wanted, x axis is the time and y axis is the average loudness of all frequencies. Keep in mind that browsers like chrome don't draw the graph properly in a background tab because it limits the refresh interval and audio analyzer output.

Demo: http://seapip.com/canvas/visualizer2

//Without var to make it a global variable accessable by the html onclick attribute 
audioElement = document.getElementById('audioElement');
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audioSrc = audioCtx.createMediaElementSource(audioElement);
var analyser = audioCtx.createAnalyser();

// Bind our analyser to the media element source.
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);

//Get frequency data (800 = max frequency)
var frequencyData = new Uint8Array(400);
//Use below to show all frequencies
//var frequencyData = new Uint8Array(analyser.frequencyBinCount);

//Create canvas
var canvas = document.getElementById("wave");
canvas.style.width = "1000px";
canvas.style.height = "100px";

//High dpi stuff
canvas.width = parseInt(canvas.style.width) * 2;
canvas.height = parseInt(canvas.style.height) * 2;

//Get canvas context
var ctx = canvas.getContext("2d");

//Set stroke color to yellow
ctx.strokeStyle = "#ffff00";

//Draw twice as thick lines due to high dpi scaling
ctx.lineWidth = 2;

//Save x and y from the previous drawing
var drawX = 0;
var drawY = 0;

//Total duration (Seconds)
var duration;

//The animation reference
var animation;

//Audio is loaded
audioElement.oncanplaythrough = function() {

    //Get duration
    duration = audioElement.duration;

    //On play
    audioElement.onplay = function() {
        //Start drawing
        drawWave();
    };

    //On pause
    audioElement.onpause = function() {
        //Stop drawing
        cancelAnimationFrame(animation);
    };

    //On ended
    audioElement.onended = function() {
        //Stop drawing
        cancelAnimationFrame(animation);

        //Clear previous drawing
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        //Clear previous x and y values
        drawX = 0;
        drawY = 0;

        //Prevent audio from looping (you can remove this if you want it to loop)
        audioElement.pause();
    };
};

//Our drawing method
function drawWave() {

    //Current time (seconds)
    var currentTime = audioElement.currentTime;

    // Copy frequency data to frequencyData array.
    analyser.getByteFrequencyData(frequencyData);

    //Total loudness of all frequencies in frequencyData
    var totalLoudness = 0;
    for(var i = 0; i < frequencyData.length; i++) {
        totalLoudness += frequencyData[i];
    }

    //Average loudness of all frequencies in frequencyData
    var averageLoudness = totalLoudness / frequencyData.length;

    //Get the previous x axis value
    var previousDrawX = drawX;

    //Scale of progress in song (from 0 to 1)
    drawX =  currentTime / duration;
    //Multiply with canvas width to get x axis value
    drawX *= canvas.width;

    //Get the previous y axis value
    var previousDrawY = drawY;

    //Scale of average loudness from (0 to 1), frequency loudness scale is (0 to 255)
    drawY = averageLoudness / 255;
    //Multiply with canvas height to get scale from (0 to canvas height)
    drawY *= canvas.height;
    //Since a canvas y axis is inverted from a normal y axis we have to flip it to get a normal y axis value
    drawY = canvas.height - drawY;

    //Draw line
    ctx.beginPath();
    ctx.moveTo(previousDrawX, previousDrawY);
    ctx.lineTo(drawX, drawY);
    ctx.stroke();

    //Animate
    animation = requestAnimationFrame(drawWave);
}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio>
<canvas id="wave"></canvas>
<div>
  <button onclick="audioElement.play()">Play the Audio</button>
  <button onclick="audioElement.pause()">Pause the Audio</button>
  <button onclick="audioElement.volume+=0.1">Increase Volume</button>
  <button onclick="audioElement.volume-=0.1">Decrease Volume</button>
</div>




Canvas visualizer example

Demo: http://seapip.com/canvas/visualizer/

//Without var to make it a global variable accessable by the html onclick attribute 
audioElement = document.getElementById('audioElement');
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audioSrc = audioCtx.createMediaElementSource(audioElement);
var analyser = audioCtx.createAnalyser();

// Bind our analyser to the media element source.
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);

//Get frequency data (400 = max frequency)
var frequencyData = new Uint8Array(400);
//Use below to show all frequencies
//var frequencyData = new Uint8Array(analyser.frequencyBinCount);

//Create canvas
var canvas = document.getElementById("wave");
canvas.style.width = "500px";
canvas.style.height = "100px";

//High dpi stuff
canvas.width = parseInt(canvas.style.width) * 2;
canvas.height = parseInt(canvas.style.height) * 2;

//Get canvas context
var ctx = canvas.getContext("2d");

//Set stroke color
ctx.strokeStyle = "#ffff00"

//Draw twice as thick lines due to high dpi scaling
ctx.lineWidth = 2;

//Animation reference
var animation;

//On play
audioElement.onplay = funtion() {
    drawWave();
};

//On pause
audioElement.onpause = funtion() {
    cancelAnimationFrame(animation);
};

//On ended
audioElement.onended = funtion() {
    cancelAnimationFrame(animation);
};

//Our drawing method
function drawWave() {
    // Copy frequency data to frequencyData array.
    analyser.getByteFrequencyData(frequencyData);

    //Draw the wave
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for(var i = 1; i < frequencyData.length; i++) {
        var x1 = canvas.width / (frequencyData.length - 1) * (i - 1);
        var x2 = canvas.width / (frequencyData.length - 1) * i;
        var y1 = canvas.height - frequencyData[i - 1] / 255 * canvas.height;
        var y2 = canvas.height - frequencyData[i] / 255 * canvas.height;
        if(x1 && y1 && x2 && y2) {
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
        }
    }

    //Animate
    animation = requestAnimationFrame(drawWave);
}


<audio id="audioElement" src="audio/Odesza - Above The Middle.mp3"></audio>
<canvas id="wave"></canvas>
<div>
  <button onclick="document.getElementById('audioElement').play()">Play the Audio</button>
  <button onclick="document.getElementById('audioElement').pause()">Pause the Audio</button>
  <button onclick="document.getElementById('audioElement').volume+=0.1">Increase Volume</button>
  <button onclick="document.getElementById('audioElement').volume-=0.1">Decrease Volume</button>
</div>




Plugins and tutorials about audio visualization:

https://wavesurfer-js.org/

http://waveformjs.org/#weird

https://www.bignerdranch.com/blog/music-visualization-with-d3-js/

https://github.com/wayou/HTML5_Audio_Visualizer

https://www.patrick-wied.at/blog/how-to-create-audio-visualizations-with-javascript-html

https://p5js.org/examples/examples/Sound_Frequency_Spectrum.php

这篇关于在 html 中播放 wav 音频文件的移动波形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 html 中播放 wav 音频文件的移动波形

基础教程推荐