Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mix Microphone+Mp3 and use it as audio source for Opentok
<html>
<head>
<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
</head>
<body>
<audio crossOrigin="anonymous" id="mp3file" controls>
<source src="helix.mp3"/>
</audio>
<div id="layoutContainer"></div>
<button onclick="startProcess()">Let the magic begin</button>
<script>
var apiKey="";
var sessionId="";
var token="";
var AudioContext = window.AudioContext;
var MediaStream = window.MediaStream;
var micstream = undefined;
var filestream = undefined;
var destination = undefined;
var micSource = undefined;
var fileSource = undefined;
var audioContext = undefined;
if (typeof navigator !== 'undefined' && typeof navigator.getUserMedia === 'undefined') {
if (typeof navigator.webkitGetUserMedia !== 'undefined') {
navigator.getUserMedia = navigator.webkitGetUserMedia;
}
if (typeof navigator.mozGetUserMedia !== 'undefined') {
navigator.getUserMedia = navigator.mozGetUserMedia;
}
}
const constraints = window.constraints = {
audio: true,
video: false
};
function startProcess(){
audioContext = new AudioContext();
navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError);
}
function handleSuccess(stream) {
micstream = stream;
var audioElem = document.getElementById("mp3file");
filestream = audioElem.captureStream? audioElem.captureStream() : audioElem.mozCaptureStream();
micSource = audioContext.createMediaStreamSource(stream);
fileSource = audioContext.createMediaStreamSource(filestream);
destination = audioDestination = self.audioContext.createMediaStreamDestination();
micSource.connect(destination);
fileSource.connect(destination);
initializeSession();
}
function handleError(error) {
console.log(error);
}
function initializeSession() {
OTSession = OT.initSession(apiKey, sessionId);
OTSession.on('streamCreated', function(event) {
subscriber = OTSession.subscribe(event.stream, 'layoutContainer', {
insertMode: 'append',
width: '100%',
height: '100%'
}, handleError);
});
OTSession.on('streamDestroyed', function(event) {
});
startPublishing();
}
function startPublishing(){
OTSession.connect(token, function(error) {
if (error) {
handleError(error);
} else {
publisher = OT.initPublisher('layoutContainer', {
insertMode: 'append',
width: '100%',
height: '100%',
videoSource: false,
audioSource: destination.stream.getAudioTracks()[0]
}, (err) => {
if (err) {
alert(err.message);
}
else{
OTSession.publish(publisher,function(error) {
if (error) {
console.log(error);
} else {
console.log('Publishing a stream.');
}
});
}
});
}
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment