javascript - 检测 WebAudio 声音结束
问题描述
我正在使用 javascript 构建收音机,我正在尝试为其提供不同的功能,但我需要能够检测到歌曲的结尾以使其正常工作。有没有办法做到这一点?
我已经尝试过我在网上找到的不同方法,比如 .ended 等,但我认为如果不使用 html 音频标签,这些方法就行不通。因此,我尝试制作一个音频标签,该标签对我的 js 收音机使用的源使用相同的数据,并获取文件长度以在结束时间停止我的 sourceNode 并制作一个新标签,但我一直将 null 作为数据返回,所以那也行不通。
我想做类似的事情:
context.onended = function() {
$.ajax({
url: '../scripts/radio.php',
data: {
attr1: 'value1'
},
success: function(data) {
console.log(data);
fileChosen = true;
setupAudioNodes();
var request = new XMLHttpRequest();
request.addEventListener("progress", updateProgress);
request.addEventListener("load", transferComplete);
request.addEventListener("error", transferFailed);
request.addEventListener("abort", transferCanceled);
request.open('GET', data, true);
request.responseType = 'arraybuffer';
// When loaded decode the data
request.onload = function() {
$("#title").html("Title");
$("#album").html("Goes");
$("#artist").html("Here");
onWindowResize();
$("#title, #artist, #album").css("visibility", "visible");
// decode the data
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
sourceNode.buffer = buffer;
sourceNode.start(0);
$("#freq, body").addClass("animateHue");
//on error
}, function(e) {
console.log(e);
});
};
request.send();
}
});
我希望它在歌曲结束时运行并播放下一个文件。如果我能得到当前播放歌曲的结束时间,它会起作用。
解决方案
为了解决上述问题,我在设置源的函数中添加了 .ended 事件:
function setupAudioNodes() {
// setup a analyser
analyser = context.createAnalyser();
// create a buffer source node
sourceNode = context.createBufferSource();
//connect source to analyser as link
sourceNode.connect(analyser);
// and connect source to destination
sourceNode.connect(context.destination);
//start updating
rafID = window.requestAnimationFrame(updateVisualization);
//I had to place a function for the .ended event inside the function sourceNode was set up.
sourceNode.onended = function() {
sourceNode.stop(0);
playFirst();
}
}
推荐阅读
- c++ - SDL2 透明背景
- python - 在没有用 python 美丽的汤挑选 br 标记后,网络抓取一些信息的困难
- c# - 弹性搜索不适用于集群模式下的基本身份验证
- r - 如何保存已使用 assign() 创建的 R 数据对象?
- javascript - 反应表单钩子如何验证选择选项
- xamarin - 我更改了 XF 应用程序中的图标。info.plist iTunes 图稿 1x 和 2x。但是当我在本地部署到手机时图标不会改变
- java - 从 AndroidStudio 中的矢量中删除挡板
- linux-kernel - 有没有办法对 Linux 内核启动选项进行硬编码?
- c++ - 为什么在 C++ 中合并两个已排序的链表时总是出现此错误?
- php - 如何为特定运输方式禁用多个支付网关