为什么decodeAudioData()在不同的操作系统上

时间:2015-12-10 12:30:35

标签: javascript html google-chrome operating-system web-audio

更新2:在此处运行脚本。单击“加载”按钮时,它将显示采样率。

function decode() {
    // If the default naming is not enabled, use the Chrome one
    if (!window.AudioContext) {
        if (!window.webkitAudioContext) {
            alert("No AudioContext found.");
        }
        window.AudioContext = window.webkitAudioContext;
    }
    var audioContext = new AudioContext();
    alert("sample rate: " + audioContext.sampleRate);
    var sourceNode;

    var BUFFER_SIZE = 1024;

    // Create buffer node and download file to buffer
    createAudioNodes();
    var fileURL = "http://plaay.in/decode-audio-data/decode-this-audio.wav";
    downloadAudioFromURL(fileURL);

    function createAudioNodes() {
        sourceNode = audioContext.createBufferSource();
        sourceNode.connect(audioContext.destination);
    }

    function downloadAudioFromURL(url) {
        var request = new XMLHttpRequest();
        request.open("GET", url, true);
        request.responseType = "arraybuffer";
        request.addEventListener("progress", updateProgress);

        request.onload = function() {
            audioContext.decodeAudioData(request.response, function(buffer) {
                setSourceBuffer(buffer);
            }, onError);
        };
        request.send();
    }

    function updateProgress(progress) {
        if (progress.lengthComputable) {
            var percentComplete = Math.round(progress.loaded / progress.total * 100);
            document.getElementById("progress").innerHTML = "Loading... " + percentComplete.toString() + "%";
        }
    }

    function setSourceBuffer(buffer) {
        var leftInBuffer = buffer.getChannelData(0);
        console.log("leftInBuffer length: " + leftInBuffer.length);
        for (var i = 0; i < leftInBuffer.length; i++) {
            console.log(leftInBuffer[i]);
        }
    }

    function onError(e) {
        console.log(e);
    }
}
<!doctype html>
<html lang="en-US">

<head>
    <meta charset="utf-8">
    <title>Decode Audio Data</title>
</head>

<body>
    <script src="decode.js"></script>
    <button id="playButton" type="button" style="height:40px;width:150px" onclick="decode()">LOAD</button>
    <p id="progress">File download progress</p>
</body>

</html>

更新:提交了问题here

我想解码音频文件并获取其原始数据以便在以下步骤中进行处理。我们的想法是使用decodeAudioData()的Web Audio API。奇怪的问题是解码结果将取决于操作系统。有没有人遇到同样的问题,或者知道原因?

我快速demo并在Mac OS(10.11)和Windows 7上进行了测试,浏览器都是Chrome(v46.0 +),但效果不同。要想象结果:

enter image description here

每个人都可以运行此demo,只需点击“加载”按钮,结果就会记录在控制台中。

2 个答案:

答案 0 :(得分:2)

他们在Windows和Chrome之间不应该有所不同。在crbug.com/new提交错误。

答案 1 :(得分:1)

最后,我发现OfflineAudioContext可以设置后期decodeAudioData()的采样率。要解码具有44.1kHz采样率的30秒长立体声音频,请创建如下所示的offlineAudioContext,并且不要忘记Safari的webkit前缀。

window.OfflineAudioContext = window.offlineAudioContext || window.webkitOfflineAudioContext;
var offlineAudioContext = new OfflineAudioContext(2, 44100 * 30, 44100);