![](/img/trans.png)
[英]How can I link different MP3 files from an <ul> playlist to the same <audio> tag?
[英]How can I detect the number of audio channels in an mp3 in an <audio> tag?
根據我的閱讀,我希望以下JavaScript代碼記錄“All is well”,但它會遇到錯誤情況:
var audio = document.createElement('audio'); var ctx = new window.AudioContext(); var source = ctx.createMediaElementSource(audio); audio.src = 'http://www.mediacollege.com/audio/tone/files/440Hz_44100Hz_16bit_30sec.mp3'; // As @padenot mentioned, this is the number of channels in the source node, not the actual media file var chans = source.channelCount; if(chans == 1) { snippet.log("All is well"); } else { snippet.log("Expected to see 1 channel, instead saw: " + chans) }
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
這可能是一個CORS問題嗎? 有沒有其他方法來確定這個mp3文件實際上是單聲道?
編輯:正如@padenot所提到的,這是源節點中的通道數,而不是實際的媒體文件
我希望有一種解決方案可以避免在記憶中解碼整個音頻文件。 在我的經驗中, decodeAudioData()
需要將整個mp3解碼為一個,這可能需要幾秒鍾。 createMediaElementSource()
允許您在收聽時流式傳輸媒體和解碼。
MediaElementAudioSourceNode
確實具有channelCount
屬性,但它引用的是AudioNode的通道數,而不是基礎HTMLMEdiaElement的通道數。
相反,您可以解碼緩沖區,並查詢其通道數,如下所示:
var xhr = new XMLHttpRequest();
xhr.open('GET', "file.mp3", true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var cx = new AudioContext() ;
cx.decodeAudioData(xhr.response, function(decodedBuffer) {
console.log(decodedBuffer.numberOfChannels);
});
}
xhr.send(null);
是的,您需要在響應中使用CORS頭才能實現此功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.