Twine Version: 2.3.16 and sugarcube 2.36.1
[also choose a Story Format tag above]
I’m trying to have ask camera permission and start recording from the user in my first passage and stop recording and download video in the last passage - this one doesn’t work. I’m using recordRTC and jquery libraries and I’m adding them via CDN. Can anyone please help me work my code?
This is the code in the javascript for the libraries:
// Include the RecordRTC library using a CDN
var recordScript = document.createElement('script');
recordScript.src = 'https://cdn.jsdelivr.net/npm/recordrtc';
document.head.appendChild(recordScript);
(function () {
'use strict';
// Check if jQuery is already loaded
if (typeof jQuery === 'undefined') {
// Create a script element
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
// Append the script element to the document body
document.body.appendChild(script);
}
})();
this is the code in my first passage:
<button id="startRecordingButton">Start Recording</button>
<<script>>
$(document).ready(function() {
$('#startRecordingButton').on('click', function() {
startRecording();
});
});
function startRecording() {
var recordRTC; // Local variable to store the RecordRTC instance
navigator.mediaDevices.getUserMedia({ video: true })
.then(function(stream) {
// Permission granted, do something with the camera stream
alert("Camera permission granted!");
// Create a new video element to display the camera stream
var videoElement = document.createElement("video");
videoElement.srcObject = stream;
videoElement.autoplay = true;
videoElement.style.position = "fixed";
videoElement.style.top = "0";
videoElement.style.right = "0";
videoElement.style.width = "200px";
videoElement.style.height = "auto";
$('body').append(videoElement);
// Create a RecordRTC instance to record the video stream
recordRTC = RecordRTC(stream, { type: 'video' });
// Start recording
recordRTC.startRecording();
// Show the download button
$('#downloadButton').show();
})
.catch(function(error) {
// Permission denied or error occurred
alert("Camera permission denied or error occurred: " + error);
});
}
<</script>>
this is the code in my last passage:
<button id="downloadButton">Download Video</button>
<<script>>
$('#downloadButton').on('click', function() {
var recordRTC; // Local variable to store the RecordRTC instance
if (typeof window.recordRTC !== 'undefined') {
recordRTC = window.recordRTC;
// Stop recording
recordRTC.stopRecording(function() {
// Create a Blob from the recorded data
var blob = recordRTC.getBlob();
// Create a download link for the Blob
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "recorded_video.webm";
document.body.appendChild(a);
// Trigger the click event on the download link
a.click();
// Clean up
URL.revokeObjectURL(url);
document.body.removeChild(a);
});
}
});
<</script>>