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!
Related
const tmi = require('tmi.js');
// Define configuration options
var x = "asdfasdf"
const opts = {
identity: {
username: 'username',
password: 'password'
},
channels: [
"rabeya74"
]
};
// Create a client with our options
const client = new tmi.client(opts);
// Register our event handlers (defined below)
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
// Connect to Twitch:
client.connect();
// Called every time a message comes in
function onMessageHandler(target, context, msg, self) {
if (self) {
return;
} // Ignore messages from the bot
// Remove whitespace from chat message
const commandName = msg.trim();
// If the command is known, let's execute it
if (commandName === '!dice') {
const num = rollDice();
client.say(target, `You rolled a ${num}`);
document.body.innerHTML = x;
console.log(`* Executed ${commandName} command`);
document.body.innerHTML = `You rolled a ${num}`;
window.onload = function() {
document.getElementById("display").innerHTML = "hello";
}
document.getElementById("display").innerHTML = "hello";
} else {
console.log(`* Unknown command ${commandName}`);
}
}
// Function called when the "dice" command is issued
function rollDice() {
const sides = 6;
return Math.floor(Math.random() * sides) + 1;
}
// Called every time the bot connects to Twitch chat
function onConnectedHandler(addr, port) {
console.log(`* Connected to ${addr}:${port}`);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="bot.js"></script>
<div id="display"></div>
</body>
</html>
I'm trying to make a small twitch javascript app that updates the HTML file when I roll a dice. I tried every version of the document.body.innerHTML file but it simply does not want to update. Is it because it's in a function? It seems to just not show anything.
You can't use require() in the browser. This code produces an error because require is undefined. Try adding a <script src="tmi.js"></script> in your <head> element.
I would like to make a web app using Firebase Hosting.
make audio file using Cloud text to speech API
upload that audio file to Cloud Storage
download that audio file from Cloud Storage to a web browser
I passed step 1 and 2, but have a trouble with step 3.
I followed this turorial.
https://firebase.google.com/docs/storage/web/download-files
I deployed my Firebase project and tested my app. I could upload audio file to Cloud Storage, but I couldn't download it. I looked at browser's console, but I couldn't find any error message. There was no message in browser's console.
Could you give me any advice? Thank you in advance.
This is my main.js
'use strict';
// Saves a new message on the Cloud Firestore.
function saveMessage() {
// Add a new message entry to the Firebase database.
return firebase.firestore().collection('messages').add({
text: messageInputElement.value,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
}).catch(function(error) {
console.error('Error writing new message to Firebase Database', error);
});
}
// Checks that the Firebase SDK has been correctly setup and configured.
function checkSetup() {
if (!window.firebase || !(firebase.app instanceof Function) || !firebase.app().options) {
window.alert('You have not configured and imported the Firebase SDK. ' +
'Make sure you go through the codelab setup instructions and make ' +
'sure you are running the codelab using `firebase serve`');
}
}
// Checks that Firebase has been imported.
checkSetup();
// Shortcuts to DOM Elements.
var messageInputElement = document.getElementById('text');
var submitButtonElement = document.getElementById('download');
// Saves message on form submit.
submitButtonElement.addEventListener('click', saveMessage);
// Create a reference from a Google Cloud Storage URI
var storage = firebase.storage();
var gsReference = storage.refFromURL('gs://advan********8.appspot.com/audio/sub.mp3')
gsReference.getDownloadURL().then(function(url) {
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
}).catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
console.log('storage/object-not-found')
break;
case 'storage/unauthorized':
console.log('storage/unauthorized')
break;
case 'storage/canceled':
console.log('storage/canceled')
break;
case 'storage/unknown':
console.log('storage/unknown')
break;
}
});
This is index.js (Cloud Functions)
const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp();
const textToSpeech = require('#google-cloud/text-to-speech');
exports.myFunction = functions.firestore
.document('messages/{id}')
.onCreate((change, context) => {
const client = new textToSpeech.TextToSpeechClient();
async function quickStart() {
// The text to synthesize
const text = 'Hello world';
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML voice gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
var bucket = admin.storage().bucket('adva********.appspot.com');
var file = bucket.file('audio/sub.mp3')
// Create the file metadata
var metadata = {
contentType: 'audio/mpeg'
};
// Performs the text-to-speech request
const [response] = await client.synthesizeSpeech(request);
return await file.save(response.audioContent, metadata)
.then(() => {
console.log("File written to Firebase Storage.")
return;
})
.catch((error) => {
console.error(error);
});
}
quickStart();
});
This is index.html
<!--./advance/index.html-->
<!doctype html>
<html lang="ja">
<head>
<meta name="robots" content="noindex">
<title>音読アプリ アドバンス</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=M+PLUS+Rounded+1c&display=swap" rel="stylesheet">
<style>
#text {width: 100%; height: 300px; font-family: 'M PLUS Rounded 1c', sans-serif; font-size: 22px;}
#download {font-family: 'M PLUS Rounded 1c', sans-serif; font-size: 28px;}
</style>
</head>
<body>
<textarea id="text" class="form-control" name="text" placeholder="ここに英文を入力してください。" maxlength="3000" minlength="1"></textarea>
<br>
<div style="text-align:center">
<input id="download" class="btn btn-primary" type="submit" value="音声をダウンロード">
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not want to serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<script src="/__/firebase/7.14.3/firebase-app.js"></script>
<script src="/__/firebase/7.14.3/firebase-auth.js"></script>
<script src="/__/firebase/7.14.3/firebase-storage.js"></script>
<script src="/__/firebase/7.14.3/firebase-messaging.js"></script>
<script src="/__/firebase/7.14.3/firebase-firestore.js"></script>
<script src="/__/firebase/7.14.3/firebase-performance.js"></script>
<script src="/__/firebase/7.14.3/firebase-functions.js"></script>
<script src="/__/firebase/init.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
browser's developer tool's Network tab
The problem is that you are likely trying to download before the file is created by your cloud function, since you are running the cloud function as a event trigger that automatically runs every time a document is created, but at the same time you are trying to download that file on your front end. This lack of syncronism creates this odd behaviour you are seeing.
In order to fix that there are a couple of things you should do:
Convert your cloud function to a http triggered function instead of a event triggered function.
This will make it so your function can be invoked by your front end after the creation of the document and before you are trying to download it, it could look like this:
exports.myFunction = (req, res) => {
//you can get the id of the document sent on the request here
const id=req.body;
...
};
Also, you might want to check this documentation for more details on this type of trigger
Create a download function and add all your code for the download to it and add synchronicity to your operations on your front-end.
With this your code will execute in the proper order, and you main.js will look like this:
// Saves a new message on the Cloud Firestore.
function saveMessage() {
// Add a new message entry to the Firebase database.
firebase.firestore().collection('messages').add({
text: messageInputElement.value,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function(docRef){
var obj = {
method: 'POST',
body: docRef.id
};
//calls function that adds to storage
fetch("YOUR_FUNTION_URL_HERE", obj).then({
//actually downloads
download();
}).catch(error) {
console.error('Failed to call cloud function', error);
});
}).catch(function(error) {
console.error('Error writing new message to Firebase Database', error);
});
}
function download(){
var storage = firebase.storage();
var gsReference = storage.refFromURL('gs://advan********8.appspot.com/audio/sub.mp3')
gsReference.getDownloadURL().then(function(url) {
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
}).catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
console.log('storage/object-not-found')
break;
case 'storage/unauthorized':
console.log('storage/unauthorized')
break;
case 'storage/canceled':
console.log('storage/canceled')
break;
case 'storage/unknown':
console.log('storage/unknown')
break;
}
});
}
// Checks that Firebase has been imported.
checkSetup();
// Shortcuts to DOM Elements.
var messageInputElement = document.getElementById('text');
var submitButtonElement = document.getElementById('download');
// Saves message on form submit.
submitButtonElement.addEventListener('click', saveMessage);
NOTE: This is all untested but it will be a good starting point for your to start the changes necessary to your code.
I hope someone may still find this useful. A hack around is to create an express server/lambda/cloud function to download file and send it back to the browser via the download method. Check bellow code
const express = require("express");
const app = express();
var fs = require("fs");
const request = require("request");
app.get("/", (req, res) => {
const { filename, fileUrl } = req.body;
const file = fs.createWriteStream("filename");
request.get(fileUrl).on("response", function (response) {
var pipe = response.pipe(file);
pipe.on("finish", function () {
res.download(filename, function (err) {
if (err) {
console.log(err); // Check error if you want
}
fs.unlink(yourFilePath, function () {
console.log("File was deleted"); // Callback
});
});
});
});
});
app.listen(3000, () => console.log("Server ready"));
I make a simple audio recording web app using Firebase Hosting. I would like to record audio on browser and upload it to Cloud Storage. When I deploy and access my app, I can record audio. However the app failed to upload the audio to Cloud Storage.
(I use Windows 10, Windows Subsystems for Linux, Debian 10.3 and Google Chrome browser. )
This is an error message in browser's console.
Uncaught
h
code: (...)
code_: "storage/invalid-argument"
message: (...)
message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File."
name: (...)
name_: "FirebaseError"
serverResponse: (...)
serverResponse_: null
__proto__: Object
This is a screenshot of browser's console.
This is index.html.
<!doctype html>
<html lang="ja">
<head>
<title>音読アプリ アドバンス</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://www.WebRTC-Experiment.com/RecordRTC.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io-stream/0.9.1/socket.io-stream.js"></script>
</head>
<body>
<div>
<button id="start-recording" disabled>Start Recording</button>
<button id="stop-recording" disabled>Stop Recording</button>
</div>
<script type="text/javascript">
const startRecording = document.getElementById('start-recording');
const stopRecording = document.getElementById('stop-recording');
let recordAudio;
startRecording.disabled = false;
console.log(startRecording)
// on start button handler
startRecording.onclick = function() {
// recording started
startRecording.disabled = true;
// make use of HTML 5/WebRTC, JavaScript getUserMedia()
// to capture the browser microphone stream
navigator.getUserMedia({
audio: true
}, function(stream) {
recordAudio = RecordRTC(stream, {
type: 'audio',
mimeType: 'audio/webm',
sampleRate: 44100, // this sampleRate should be the same in your server code
// MediaStreamRecorder, StereoAudioRecorder, WebAssemblyRecorder
// CanvasRecorder, GifRecorder, WhammyRecorder
recorderType: StereoAudioRecorder,
// Dialogflow / STT requires mono audio
numberOfAudioChannels: 1,
// get intervals based blobs
// value in milliseconds
// as you might not want to make detect calls every seconds
timeSlice: 4000,
// only for audio track
// audioBitsPerSecond: 128000,
// used by StereoAudioRecorder
// the range 22050 to 96000.
// let us force 16khz recording:
desiredSampRate: 16000
});
recordAudio.startRecording();
stopRecording.disabled = false;
}, function(error) {
console.error(JSON.stringify(error));
});
};
// on stop button handler
stopRecording.onclick = function() {
// recording stopped
startRecording.disabled = false;
stopRecording.disabled = true;
// stop audio recorder
recordAudio.stopRecording(function() {
// after stopping the audio, get the audio data
recordAudio.getDataURL(function(audioDataURL) {
var file = {
name: 'speech.wav',
audio: {
type: recordAudio.getBlob().type || 'audio/wav',
dataURL: audioDataURL
}
};
// Create a root reference
var storageRef = firebase.storage().ref();
// Create the file metadata
var metadata = {
contentType: 'audio/wav'
};
// Upload file and metadata to the object 'images/mountains.jpg'
var uploadTask = storageRef.child('audio/' + file.name).put(file, metadata);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function(snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
}, function() {
// Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});
});
});
};
</script>
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not want to serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<script src="/__/firebase/7.14.3/firebase-app.js"></script>
<script src="/__/firebase/7.14.3/firebase-auth.js"></script>
<script src="/__/firebase/7.14.3/firebase-storage.js"></script>
<script src="/__/firebase/7.14.3/firebase-messaging.js"></script>
<script src="/__/firebase/7.14.3/firebase-firestore.js"></script>
<script src="/__/firebase/7.14.3/firebase-performance.js"></script>
<script src="/__/firebase/7.14.3/firebase-functions.js"></script>
<script src="/__/firebase/init.js"></script>
</body>
</html>
Could you give me any advices?
Thank you in advice.
I don't know much about the .wav file but you seem to be trying to store an object instead of a blob or a file that Firebase Storage is expecting. Try creating a var blob = recordAudio.getBlob() and replace file in your put() function with blob instead.
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>
I'm working on mobile device (iOS). I develop a hybrid application using HTML/CSS/Javascript.
I have this code founded on Apache Cordova API :
<!DOCTYPE html>
<html>
<head>
<title>Capture Audio</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureAudio() {
// Launch device audio recording application,
// allowing user to capture up to 2 audio clips
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
</head>
<body>
<button onclick="captureAudio();">Capture Audio</button> <br>
</body>
</html>
I can capture my voice with it and in theory upload it to
http://my.domain.com/upload.php
But I wonder how to adapt this code to upload file on my Dropbox . Is it possible to upload file to Dropbox as easy as that ?
As #sinaneker mentioned, you can do this server-side with PHP (or other languages).
But you can also do this directly from JavaScript using Dropbox's JavaScript library: https://github.com/dropbox/dropbox-js