html video player freezes after adding mp4 video arraybuffer to media source - javascript

I tried to handle video data from api with javascript, the api response is ok but the player doesn't
work as expected and when I play the video the console throw an error.
DOMException: The element has no supported sources.
Although video data is available the array buffer seem to be not pushed into media source yet
Here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Hello</h1>
<video id="video" controls autoplay></video>
</body>
</html>
<script>
window.onload = function() {
var mime = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
const videoTag = document.getElementById("video");
if (
"MediaSource" in window &&
MediaSource.isTypeSupported(mime)
) {
var mediaSource = new MediaSource();
//console.log(mediaSource.readyState);
videoTag.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
console.error("Unsupported MIME type or codec: ", mime);
}
function sourceOpen(e) {
var msource = this;
console.log(msource.readyState);
// URL.revokeObjectURL(vidElement.src);
var sourceBuffer = msource.addSourceBuffer(mime);
var videoUrl = "https://vjs.zencdn.net/v/oceans.mp4";
fetch(videoUrl)
.then(function(response) {
return response.arrayBuffer();
})
.then(function(arrayBuffer) {
console.log("object", arrayBuffer.byteLength);
sourceBuffer.addEventListener("updateend", function(_) {
console.log(msource.readyState);
if (!sourceBuffer.updating &&
mediaSource.readyState === "open"
) {
msource.endOfStream();
}
videoTag.play();
});
sourceBuffer.appendBuffer(arrayBuffer);
})
.catch(e => console.log(e));
}
};
</script>

Related

How to send the data from the script to HTML page?

I am using Firebase to get the data
code:
const admin = require('firebase-admin');
const serviceAccount = require("C:/Users/santo/Downloads/bestmpos-firebase-adminsdk.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let fs = admin.firestore();
let auth = admin.auth();
const listAllUsers = async (nextPageToken) => {
try {
let result = await auth.listUsers(100, nextPageToken);
result.users.forEach((userRecord) => {
start(userRecord.toJSON())
});
if (result.pageToken) {
listAllUsers(result.pageToken);
}
} catch(ex) {
console.log('Exception listing users:', ex.message);
}
}
async function first(){
await listAllUsers();
}
first();
async function start (object){
const info = await fs.collection('users').doc(object.uid).get();
if (!info.exists) {
console.log('No document');
} else {
console.table([info.data()]);
document.getElementById("greeting").innerHTML = info.data().toString();
}
}
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="app3.js"></script>
</head>
<body>
<p id="greeting"></p>
</body>
</html>
but I want to send data console.log(info.data()) to HTML page to simply show information,
How can I do that, I don't want to use react or any other
can someone help me?
and I also is this Nodejs or plain javascript?
You can use innerHTML to sent data in your html.
Like this:
document.getElementById("yourElementId").innerHTML = info.data();
This is working for me:
<p id="greeting">
</p>
<script>
document.getElementById("greeting").innerHTML = "test"
</script>

rtsp streaming node js ip camera jsmpeg fail

Connected to an ip camera, but it's problem like a picture
when running node app.js "frame= 1970 fps=2.0 q=7.6 size= 22457kB time=00:16:25.00 bitrate= 186.8kbits/s dup=0 drop=3 speed=1.01x"
When executing index.html "name: New WebSocket Connection (1 total)kB time=00:00:43.00 bitrate= 147.0kbits/s speed=1.28x"
but, there are times when the camera does not appear on the canvas, and it is printed like the picture below
app.js
// const onvif = require('node-onvif');
// console.log('Start the discovery process.');
// // Find the ONVIF network cameras.
// // It will take about 3 seconds.
// onvif.startProbe().then((device_info_list) => {
// console.log(device_info_list.length + ' devices were found.');
// // Show the device name and the URL of the end point.
// device_info_list.forEach((info) => {
// console.log('- ' + info.urn);
// console.log(' - ' + info.name);
// console.log(' - ' + info.xaddrs[0]);
// });
// }).catch((error) => {
// console.error(error);
// });
///////////////////////////////////////
// const onvif = require('node-onvif');
// // Create an OnvifDevice object
// let device = new onvif.OnvifDevice({
// xaddr: 'http://192.168.88.4:8081/onvif/device_service',
// user : 'admin',
// pass : 'tmzkdl123$'
// });
// // Initialize the OnvifDevice object
// device.init().then(() => {
// // Get the UDP stream URL
// let url = device.getUdpStreamUrl();
// console.log(url);
// }).catch((error) => {
// console.error(error);
// });
/////////////////////////////////////////
Stream = require('node-rtsp-stream')
stream = new Stream({
name: 'name',
streamUrl: 'rtsp://192.168.88.8:554/0/onvif/profile1/media.smp',
wsPort: 9900,
ffmpegOptions: { // options ffmpeg flags
'-stats': '', // an option with no neccessary value uses a blank string
'-r': 30 // options with required values specify the value after the key
}
})
index.html
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>rtsp</title>
<div><canvas id="video" width="640" height="360"></canvas></div>
<script type="text/javascript" src="jsmpeg.js"></script>
<script type="text/javascript">
var canvas = document.getElementById('video');
var ws = new WebSocket("ws://192.168.88.174:9900");
var player = new jsmpeg(ws, {canvas:canvas, autoplay:true, audio:false, loop:true});
</script>
</head>
<body>
</body>
</html>
image url
enter image description here
I had this problem too but solved that,
you must download jsmpeg.min.js from https://jsmpeg.com/
and replace it with jsmpeg.js file then change this line
<script type="text/javascript" src="jsmpeg.js"></script>
to
<script type="text/javascript" src="jsmpeg.min.js"></script>
after that clear this line
var ws = new WebSocket("ws://192.168.88.174:9900");
and change this line
var player = new jsmpeg(ws, {canvas:canvas, autoplay:true, audio:false, loop:true});
to this:
var player = new JSMpeg.Player("ws://192.168.88.174:9900", {canvas:canvas, autoplay:true, audio:false, loop:true});
your problem must be solved!

WebRTC error while creating video chat app

I am getting this error on console while refreshing the page.. Everythng else works fine the Chats and everthing.. just the streaming part is not working
NotSupportedError: MediaStreamError
at module.exports (http://192.168.1.10:9966/index.js:3081:17)
at Object.1.getusermedia (http://192.168.1.10:9966/index.js:4:1)
at o (http://192.168.1.10:9966/index.js:1:265)
at r (http://192.168.1.10:9966/index.js:1:431)
at http://192.168.1.10:9966/index.js:1:460
while creating a video chat app
This is my index.js
var getUserMedia = require('getusermedia')
getUserMedia({video: true, audio: false}, function (err, stream) {
var Peer = require('simple-peer')
var peer = new Peer({
initiator: location.hash === '#init',
trickle: false,
stream: stream
})
peer.on('signal', function (data) {
document.getElementById('yourId').value = JSON.stringify(data)
})
document.getElementById('connect').addEventListener('click', function () {
var otherId = JSON.parse(document.getElementById('otherId').value)
peer.signal(otherId)
})
document.getElementById('send').addEventListener('click', function () {
var yourMessage = document.getElementById('yourMessage').value
peer.send(yourMessage)
})
peer.on('data', function (data) {
document.getElementById('messages').textContent += data + '\n'
})
peer.on('stream', function (stream) {
var video = document.createElement('video')
document.body.appendChild(video)
video.src = window.URL.createObjectURL(stream)
video.play()
})
})
This is my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CHatting Video</title>
</head>
<body>
<label>Your ID:</label><br/>
<textarea id="yourId"></textarea><br/>
<label>Other ID:</label><br/>
<textarea id="otherId"></textarea>
<button id="connect">connect</button>
<br/>
<label>Enter Message:</label><br/>
<textarea id="yourMessage"></textarea>
<button id="send">send</button>
<pre id="messages"></pre>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
When I send a message to other browser it works fine but for video chat it does not work
Any Idea on how to fix this.????
I got the error..
I was using getUserMedia instead of navigator.getUserMedia
getUserMedia has been deprecated.

Uploading audio data from a web page to a server

I am trying to upload audio data from a web page to a server and find it more difficult than it should be.
Here is my test page, it has a button and when it is clicked, a voice recording of 5 seconds starts, then it is played back and finally the sound data should be uploaded to the server.
The voice recording and play back parts are working fine.
The upload to the server is not completely working.
The code I have is totally visible below. I put the whole file (called "GetAudio.php") on purpose, so anyone can easily copy-paste it to try.
Here is what goes wrong: the file created on the server called "Audio.data", contains 4 characters, namely:
blob
This is not what I want. I want the file to contain the actual sound data that has been recorded locally. Can someone tell me where my code is missing some important thing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Record&Upload Trial</title>
</head>
<body>
<div>
<h2>Five seconds voice record and upload.</h2>
<p>
<button id=startRecord><h3>Start the voice recording</h3></button><br/>
<audio id="player" controls></audio>
<p id="XMLH"></p>
</p>
</div>
<?php
// Server side code:
if ($_POST['AudioData']) {
$myfile = fopen("Audio.data", "w");
fwrite($myfile, $_POST['AudioData']);
fclose($myfile);
}
?>
<script>
startRecord.onclick = e => {
startRecord.disabled = true;
audioChunks = [];
rec.start();
setTimeout(() => {
rec.stop();
startRecord.disabled = false;
}, 5000);
}
var player = document.getElementById('player');
var handleSuccess = function(stream) {
rec = new MediaRecorder(stream);
rec.ondataavailable = e => {
audioChunks.push(e.data);
if (rec.state == "inactive") {
let blob = new Blob(audioChunks,{type:'audio/x-mpeg-3'});
player.src = URL.createObjectURL(blob);
player.controls=true;
player.autoplay=true;
// The code below intends to upload the sound file to the server.
// But it is partly (or completely) wrong and does not work.
var xhr = new XMLHttpRequest();
var params = 'AudioData=blob';
xhr.open('POST', 'GetAudio.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
}
}
};
navigator.mediaDevices.getUserMedia({audio:true})
.then(handleSuccess);
</script>
</body>
</html>

Simple way of displaying images from parse.com database using javascript

I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});

Categories

Resources