html5-audio之HTML5 音频 : createMediaElementSource breaks audio output

jackei 阅读:89 2025-05-04 20:05:19 评论:0

我正在学习 webgl,我正在通过 this 教程从 mp3 文件中提取频率,以便它们可以被可视化。

我让它在给定一个 mp3 文件的地方工作,它播放文件。但是如果我尝试使用 createMediaElementSource 连接到 AudioContext 的分析器来获取频率数据,它不起作用。

Fiddle

JS:

window.onload = function(e) {        
    document.getElementById('music-files').addEventListener('change', selectMusic, false); 
} 
 
var musicFiles = []; 
var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); 
var audio; 
var audioSrc; 
var analyser; 
var bufferLength; 
var dataArray; 
 
function selectMusic(e) {    
    musicFiles = e.target.files;     
} 
 
function getFreq(){ 
    requestAnimationFrame(getFreq); 
    analyser.getByteFrequencyData(dataArray); 
    console.log(">>>>>>>>>>>>>>>"); 
    console.log(dataArray[240]) 
} 
 
function play(){     
    var num = Math.floor(Math.random()*musicFiles.length); 
    console.log("playing=" + num); 
    var musicFile = URL.createObjectURL(musicFiles[num]);  
    $("#music").attr("src", musicFile); 
    document.getElementById('music').play(); 
 
    audio = document.getElementById('music'); 
    audioSrc = audioCtx.createMediaElementSource(audio);     
    analyser = audioCtx.createAnalyser(); 
    audioSrc.connect(analyser); 
    bufferLength = analyser.frequencyBinCount; 
    dataArray = new Uint8Array(bufferLength); 
    getFreq(); 
} 
 
function stop(){ 
    document.getElementById('music').pause(); 
} 

如果你看一下 fiddle ,你可以选择一个 mp3 文件并点击播放,它会在浏览器控制台中记录一个频段,但没有声音(至少在我的电脑上),这可能意味着它正在播放歌曲,但没有声音。但是如果你在下面评论这些行,它会播放这首歌,我可以听到它。

Fiddle with commented code
/*audioSrc = audioCtx.createMediaElementSource(audio);   
    analyser = audioCtx.createAnalyser(); 
    audioSrc.connect(analyser); 
    bufferLength = analyser.frequencyBinCount; 
    dataArray = new Uint8Array(bufferLength); 
    getFreq();*/ 

我的设置:Windows 10/Chrome52

任何有关此问题的建议表示赞赏。谢谢你。

请您参考如下方法:

没有声音,因为当您在元素上 createMediaElementSource 时,它​​会断开输出。 (这可以让您分析或处理音频,而不会在未经处理的情况下输出。)您需要做的就是:

audioSrc.connect(audioCtx.destination); 

在您将 audioSrc 连接到分析仪之后。


标签:HTML5
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号