gpt4 book ai didi

javascript - 使用 HTMLMediaElement 向后播放音频

转载 作者:太空狗 更新时间:2023-10-29 15:49:38 26 4
gpt4 key购买 nike

我正在尝试在 chrome 中成功加载和播放音频文件,但我无法向后播放:

      audio = new Audio('http://mathweirdo.com/bingo/audio/buzzer.mp3');
audio.playbackRate = -1;
audio.currentTime = audio.duration; // I have tried ommiting this line
audio.play()

这不会产生声音,只会触发一个 timeupdate 事件。

最佳答案

目前不支持使用负值,因此您必须手动加载和反转缓冲区。

请注意,这将需要启用 CORS 的音频源(示例中的音频源不是,因此我无法设置现场演示)。这是执行此操作的一种方法:

  • 通过 AJAX 加载数据(这需要为音频文件启用 CORS)
  • 让浏览器将缓冲区解析成音频缓冲区
  • 获取 channel 缓冲区(引用)
  • 反转缓冲区
  • 初始化音频缓冲区并播放

这当然会限制你一些,因为你不能再使用音频元素了。您必须通过手动添加控件和代码来支持您想要的功能。

// load audio as a raw array buffer:
fetch("http://mathweirdo.com/bingo/audio/buzzer.mp3", process);

// then process the buffer using decoder
function process(file) {
var actx = new (window.AudioContext || window.webkitAudioContext);
actx.decodeAudioData(file, function(buffer) {

var src = actx.createBufferSource(), // enable using loaded data as source
channel, tmp, i, t = 0, len, len2;

// reverse channels
while(t < buffer.numberOfChannels) { // iterate each channel
channel = buffer.getChannelData(t++); // get reference to a channel
len = channel.length - 1; // end of buffer
len2 = len >>> 1; // center of buffer (integer)
for(i = 0; i < len2; i++) { // loop to center
tmp = channel[len - i]; // from end -> tmp
channel[len - i] = channel[i]; // end = from beginning
channel[i] = tmp; // tmp -> beginning
}
}

// play
src.buffer = buffer;
src.connect(actx.destination);
if (!src.start) src.start = src.noteOn;
src.start(0);
},
function() {alert("Could not decode audio!")}
)
}

// ajax loader
function fetch(url, callback) {
var xhr = new XMLHttpRequest();
try {
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.onerror = function() {alert("Network error")};
xhr.onload = function() {
if (xhr.status === 200) callback(xhr.response);
else alert(xhr.statusText);
};
xhr.send();
} catch (err) {alert(err.message)}
}

关于javascript - 使用 HTMLMediaElement 向后播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29238549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com