WebRTC Play Audio Input as Microphone

≡放荡痞女 提交于 2019-12-03 15:50:16

Here is a demo that may help you stream mp3 or wav using chrome:

Here is, how it is written:

And source code of the demo:

Use in 3rd party WebRTC applications

window.AudioContext = window.AudioContext || window.webkitAudioContext;

var context = new AudioContext();
var gainNode = context.createGain();
gainNode.connect(context.destination);

// don't play for self
gainNode.gain.value = 0;

document.querySelector('input[type=file]').onchange = function() {
    this.disabled = true;

    var reader = new FileReader();
    reader.onload = (function(e) {
        // Import callback function that provides PCM audio data decoded as an audio buffer
        context.decodeAudioData(e.target.result, function(buffer) {
            // Create the sound source
            var soundSource = context.createBufferSource();

            soundSource.buffer = buffer;
            soundSource.start(0, 0 / 1000);
            soundSource.connect(gainNode);

            var destination = context.createMediaStreamDestination();
            soundSource.connect(destination);

            createPeerConnection(destination.stream);
        });
    });

    reader.readAsArrayBuffer(this.files[0]);
};

function createPeerConnection(mp3Stream) {
    // you need to place 3rd party WebRTC code here
}

Updated at: 5:55 PM - Thursday, August 28, 2014

Here is how to get mp3 from server:

function HTTP_GET(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.send();

    xhr.onload = function(e) {
        if (xhr.status != 200) {
            alert("Unexpected status code " + xhr.status + " for " + url);
            return false;
        }

        callback(xhr.response); // return array-buffer
    };
}

// invoke above "HTTP_GET" method
// to load mp3 as array-buffer

HTTP_GET('http://domain.com/file.mp3', function(array_buffer) {

    // Import callback function that provides PCM audio data decoded as an audio buffer
    context.decodeAudioData(array_buffer, function(buffer) {
        // Create the sound source
        var soundSource = context.createBufferSource();

        soundSource.buffer = buffer;
        soundSource.start(0, 0 / 1000);
        soundSource.connect(gainNode);

        var destination = context.createMediaStreamDestination();
        soundSource.connect(destination);

        createPeerConnection(destination.stream);
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!