如何用JavaScript检查远程音频流是否包含元数据?

前端开发 2026-07-12

使用HTML5的 audio元素在未知的远程流媒体上效果不佳:

const playStreamFromUrl = async (musicUrl) => {
    const audioPlayer = document.getElementById('audio-player-id');
    if (musicUrl && audioPlayer) {
        audioPlayer.src = musicUrl;
        audioPlayer.addEventListener("loadedmetadata", () => {
            // Access and display duration
            const title = audioPlayer.title;
            const duration = audioPlayer.duration;
            console.log('title',title,'duration',duration);
        });
        audioPlayer.play();
    } else {
        console.error('Please enter a valid music URL.', musicUrl, audioPlayer?.id);
    }
}

而响应是:

title <empty string> duration Infinity cal006.js:34:21

解决方案

哥们,我想你搞错了,你得到的响应并不是一个bug,只是你把信息问错了“对象”。让我解释一下,我要表达的意思是,你把信息问给了一个“播放器”,它既不知道标题也不知道时长,它只是播放音乐。如果你想要得到这些数据,我能想到的最简单的解决办法大概是这样的:

setInterval(async () => {
    const res = await fetch('http://stream.sth.com/status-json.xsl'); // you should replace this too
    const data = await res.json();
    console.log('Listening to:', data.currentTrack.title); // this changes you should  
    // console log the data before to check
}, 10000);

如果这对你有帮助,请告诉我 :)

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章