Javascript `onerror` is not getting fired - javascript

Please have a look at the code below:
function longSentenceSpeak(text)
{
var url = "http://www.translate.google.com/translate_tts?tl=en&q="+finalString;
var url2 = "http://www.translate.google.com/translate_tts?tl=sp&q="+finalString;
var audio = document.getElementById('audio');
var source = document.getElementById('source');
source.src=url;
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
audio.onerror = function()
{
var url2 = "http://translate.google.com/translate_tts?tl=en&q="+text;
var audio = document.getElementById('audio');
var source = document.getElementById('source');
source.src = url2;
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
};
}
Below is my HTML:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="scripts/TTS.js"></script>
<script>
function longText()
{
longSentenceSpeak("hello world ");
}
</script>
</head>
<body>
<audio id="audio">
<source id="source" src="" type="audio/mp3" />
</audio>
<div><button onclick="longText()">Click me</button></div>
</body>
</html>
However this gives this error, even though it should handle it:
Failed to load resource: the server responded with a status of 404 (Not Found) (12:49:15:455 | error, network)
at http‍://www.translate.google.com/translate_tts?tl=en&q=hello
What I want to do is, if this error occurred, I want to use var url2 instead of var url in function longSentenceSpeak(text). How can I do this?

The error event doesn't bubble and in this case, it will fire on the <source> elements.
You thus need to listen to it from there:
function longText() {
var audio = document.getElementById('audio');
var source = document.getElementById('source');
source.src = '/foo.bar';
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
source.onerror = function() {
console.log('handling error event');
};
}
<audio id="audio">
<source id="source" src="" type="audio/mp3" />
</audio>
<div><button onclick="longText()">Click me</button></div>

Related

How upload captured image file to sever in java script HTML PHP

I working on a project where user capture photo from camera and show captured photo, but I want upload That Photo to server . How we can upload that image file to server. I am new please help me.
please help me how we upload image file to server. I tried much but can not upload successfully.
<html>
<head>
<title>NigraniSof</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
</head>
<body>
<button id="start-camera">Start Camera</button>
<video id="video" width="320" height="240" autoplay></video>
<button id="click-photo">Click Photo</button>
<div id="dataurl-container">
<canvas id="canvas" width="320" height="240"></canvas>
<div id="dataurl-header">Image Data URL</div>
<textarea id="dataurl" readonly></textarea>
</div>
<script>
let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");
let dataurl = document.querySelector("#dataurl");
let dataurl_container = document.querySelector("#dataurl-container");
camera_button.addEventListener('click', async function() {
let stream = null;
try {
stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
}
catch(error) {
alert(error.message);
return;
}
video.srcObject = stream;
video.style.display = 'block';
camera_button.style.display = 'none';
click_button.style.display = 'block';
});
click_button.addEventListener('click', function() {
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
let image_data_url = canvas.toDataURL('image/jpeg');
dataurl.value = image_data_url;
dataurl_container.style.display = 'block';
});
</script>
</body>
</html>
you can add the canvas to an img tag for capturing and then you can take the image value using file reader method of javascript ,from that u will get the file blob which u can pass to php function using Ajax call. After that u can access that file blob in php which u can save to your server as well.

Video stream is not sent through my RTCPeerConnection

So I've put up this little test code modeling what's going on with the real version of what i have. In it I have set up 2 peer connections in the same file, each having a dedicated video element on the html. The problem is, when i start sharing the screen, the stream is not being shown on the other peer (peer2), which is the same problem I get in the real version of the code.
Here is the js code
'use strict';
const video1 = document.getElementById('video1');
const video2 = document.getElementById('video2');
let peer1 = new RTCPeerConnection();
let peer2 = new RTCPeerConnection();
peer1.onicecandidate = ev => {
console.log('peer1 oncandidate event');
if (ev.candidate) {
const c = new RTCIceCandidate(ev.candidate);
peer2.addIceCandidate(c);
}
};
peer2.onicecandidate = ev => {
console.log('peer2 oncandidate event');
if (ev.candidate) {
const c = new RTCIceCandidate(ev.candidate);
peer1.addIceCandidate(c);
}
};
peer2.onaddtrack = ev => addStreamSource;
function startVideoStream() {
const videoOptions = {
video: true,
audio: true
};
navigator.mediaDevices.getDisplayMedia(videoOptions)
.then(gotLocalMediaStream)
.catch(logError);
}
function gotLocalMediaStream(stream) {
console.log('setting the stream');
console.log(stream.getTracks());
peer1.addTrack(stream.getTracks()[0]);
video1.srcObject = stream;
peer1.createOffer()
.then(desc => {
peer1.setLocalDescription(desc);
peer2.setRemoteDescription(desc);
peer2.createAnswer()
.then(des => {
peer2.setLocalDescription(des);
peer1.setRemoteDescription(des);
})
.catch(logError);
})
.catch(logError);
}
function addStreamSource(event) {
console.log('ADDING STREAM SOURCE:');
video2.srcObject = event.streams[0];
}
function logError(e) {
console.error(`Bad thing: ${e}`);
}
function logSuccess() {
console.log('Promise Success!');
}
index.html
<html>
<head>
<title>Pretty cinema</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1 style="text-align:center;" id="text">
Pretty video streaming service
</h1>
<br />
<div id="vids">
<video id="video1" autoplay controls>
<source type='video/mp4' ; codecs="H.264" />
</video>
<video id="video2" autoplay controls>
<source type='video/mp4' ; codecs="H.264" />
</video>
</div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="./checking_peers.js"></script>
<div>
<div class="buttonsDiv">
<button onclick="startVideoStream()" type="button">Share</button>
</div>
</div>
</body>
</html>
important:
Already found the solution.
Simple explanation: I needed to create a MediaStream from the track received on peer2.
peer2.ontrack = event => {
const video = new MediaStream([event.track]);
video2.srcObject = video;
};
More details: The moment the two peers are connected (they've exchanged offer-answer's and ICE candidates) if you add a track on one end (peer1), the other end (peer2) is going to receive an event with the track in it if you've overriden the method ontrack of the peer2. You access the track as event.track. From that track you can create a MediaStream object by calling new MediaStream() and passing it an array of all tracks you want to base your stream on. That newly created stream can serve as the source for your video element, assign it with videoElement.srcObject = theMediaStream;.
Also: There was a problem with the way I set up the ICECandidate responses, so look closely into the code, it's written correctly here, might be you're having the same problem.

Trying to use EXIF.js to return GPS coords when a jpg image is clicked

I'm trying to add javascript functionality that will return gps coordinates from exif data when the user clicks on a jpg displayed on the page. (Will use that to open a google map). I have managed to produce a working example when the script is inline in the html file, but not when trying to use a separate script file, getCoords.js
Found a similar question here: How to pass images from server to function in JavaScript?
What I'm trying to do is pass the src attribute from the html click event into the script. The script is getting the src, I can print that to the console and launch the jpg in devtools by clicking on the link in the console. But it doesn't seem to be even trying to run
EXIF.getData(my_image, function() {...
Here's the HTML:
<html lang="en">
<head>
<title>Map Test Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="styles.css" rel="stylesheet">
<script src="getCoords.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.min.js">
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBMLVQ6kCIfX4c8vVHa0qOf8P87DxCvt2w">
</script>
</head>
<body>
<picture>
<source media="(min-width: 750px)" srcset="images/van_from_erp2_L.jpg 2x, images/van_from_erp2_m.jpg 1x" />
<source media="(min-width: 450px)" srcset="images/van_from_erp2_m.jpg" />
<img src="images/van_from_erp2_s.jpg" id="hiking_0" alt="View of Vancouver from ridge" onclick='getCoords(src)'>
</picture>
<picture>
<source media="(min-width: 750px)" srcset="images/creek_1_l.jpg 2x, images/creek_1_m.jpg 1x" />
<source media="(min-width: 450px)" srcset="images/creek_1_m.jpg" />
<img src="images/creek_1_s.jpg" id="hiking_1" alt="forest creek image" onclick='Hello(id)'>
</picture>
<!--div id="map"></div-->
</body>
</html>
and here's the script:
function getCoords(source) {
console.log(source);
//pass image to EXIF.js to return EXIF data (EXIF.js sourced from github)
let my_image = new Image();
my_image.src = source;
console.log("hello from line 7");
EXIF.getData(my_image, function() {
console.log("Hello from line 9");
myData = this;
console.log(myData.exifdata);
// get latitude from exif data and calculate latitude decimal
var latDegree = myData.exifdata.GPSLatitude[0].numerator;
var latMinute = myData.exifdata.GPSLatitude[1].numerator;
var latSecond = myData.exifdata.GPSLatitude[2].numerator;
var latDirection = myData.exifdata.GPSLatitudeRef;
var latFinal = ConvertDMSToDD(latDegree, latMinute, latSecond, latDirection);
//console.log(latFinal);
// get longitude from exif data and calculate longitude decimal
var lonDegree = myData.exifdata.GPSLongitude[0].numerator;
var lonMinute = myData.exifdata.GPSLongitude[1].numerator;
var lonSecond = myData.exifdata.GPSLongitude[2].numerator;
var lonDirection = myData.exifdata.GPSLongitudeRef;
var lonFinal = ConvertDMSToDD(lonDegree, lonMinute, lonSecond, lonDirection);
//console.log(lonFinal);
let site = [latFinal, lonFinal];
console.log(site);
return(site);
// Create Google Maps link for the location
//document.getElementById('map-link').innerHTML = 'Google Maps';
});
//};
function ConvertDMSToDD(degrees, minutes, seconds, direction) {
var dd = degrees + (minutes/60) + (seconds/360000);
if (direction == "S" || direction == "W") {
dd = dd * -1;
}
return dd;
}
}
Put EXIF.getData(my_image, function() {...} inside the image onload function:
my_image.onload = function() {
EXIF.getData(my_image, function() {...}
}
Note that you have to wait for the image to be completely loaded,
before calling getData or any other function. It will silently fail
otherwise. Docs

Changing src attribute in video tag with json data

I'm trying to make a video player with HTML and JavaScript that will play a series of videos, one after another, until all 6 have been played. The URLs for the videos are stored in an array and map in a .json file called clips.json.
The data in the file is below:
[
{
"id":"ashklasd132asddfgdf",
"name": "War on Drugs continues",
"description":"Losses continue in agressive raid on local property",
"content-url": "http://buffalogrove.sat.iit.edu/Kitty.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/dogs_friends-t2.jpg"
},
{
"id":"asdasd132asddf667jf",
"name": "Parlimentary Proceedings",
"description":"World Leaders meet to determine the latest policies on climate change relief",
"content-url": "http://buffalogrove.sat.iit.edu/Clouds%2038%20Timelapse.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/colorful_clouds-t2.jpg"
},
{
"id":"123dfg6132asddfgdz",
"name": "Weather for March 22nd 2015",
"description":"Join Jeremy Brown for today's weather",
"content-url": "http://buffalogrove.sat.iit.edu/Clouds-Time_lapse_22.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/hidden_lagoon-t2.jpg"
},
{
"id":"pzxc87asdkjl44h7h",
"name": "Taking a walk on the wide-side",
"description":"Cook Counties latest conservation efforts led to a new discovery",
"content-url": "http://buffalogrove.sat.iit.edu/Flower_4.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/nature_scenes_3-t2.jpg"
},
{
"id":"mkiaasdsjdh7asd8889",
"name": "Musical Stunner",
"description":"Local musician proves nay-sayers wrong by providing ample range",
"content-url": "http://buffalogrove.sat.iit.edu/Piano_keys.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/turkey_karadeniz_region-t2.jpg"
},
{
"id":"zklsjdpoiqwehbhfyvfy6h",
"name": "H-Diddy Represent",
"description":"The newest Album from H-Diddy",
"content-url": "http://buffalogrove.sat.iit.edu/Pigeon.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/nanxiang_ancient_town_shanghai_china-t2.jpg"
},
]
I'm having trouble changing the src attribute after the video from the URL is finished. After the video plays the first video, it stops, and doesn't go on to the 2nd one. I don't know if it's because I'm calling the JSON data wrong with my AJAX get request or something else, but if someone could help me solve this issue, I'd greatly appreciate it.
My HTML code with embedded JavaScript is below:
<!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">
<meta name="description" content="">
<meta name="author" content="">
<title>IIT News</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.starter-template {
padding: 40px 15px;
text-align: center;
}
</style>
<script type="text/javascript" src="/myJS.js" language="javascript"> </script>
</head>
<body onload="loadFunction()">
<div class="container">
<div class="hook">
<video onended="playNext()" width="640" height="480" id="myVideo" controls autoplay>
<!--<source src="parsedData[0].['content-url'][conUrlCount]" type="video/mp4"></source>-->
<source src="http://buffalogrove.sat.iit.edu/Kitty.mp4" type="video/mp4"></source>
</video>
</div><!-- /.hook -->
</div><!-- /.container-->
</body>
</html>
myJS.js is below
var conUrlCount = 0;
var myVideo = document.getElementById("myVideo");
//parsedData should be declared outside the function scope since we want it to be accessible from outside
var parsedData;
var callback = function (text) {
//parsedData = JSON.stringify(JSON.parse(text));
parsedData = JSON.parse(text);
conUrlCount = 0;
//after load play the first video
playNext();
};
//when page is loaded, data in json file is parsed and returned
function loadFunction() {
//returning json data
ajax.get("clips.json", callback);
};
function playNext() {
if (!parsedData) {
return
}
var myVideo = document.getElementById("myVideo");
myVideo.src = parsedData[conUrlCount]['content-url'];
myVideo.play();
conUrlCount++;
};
One problem is the json object is a local variable to the callback method, make it a global one
<video onended="playNext()" width="640" height="480" id="myVideo" controls
autoplay>
then
var conUrlCount = 0;
var myVideo = document.getElementById("myVideo");
//parsedData should be declared outside the function scope since we want it to be accessible from outside
var parsedData;
var callback = function (text) {
parsedData = JSON.parse(text);
conUrlCount = 0;
//after load play the first video
playNext();
};
//when page is loaded, data in json file is parsed and returned
function loadFunction() {
//returning json data
ajax.get("clips.json", callback);
};
function playNext() {
if (!parsedData) {
return
}
var myVideo = document.getElementById("myVideo");
myVideo.src = parsedData[conUrlCount]['content-url'];
myVideo.play();
conUrlCount++;
}
Demo: Fiddle

How do I add new Video entirely from JavaScript?

I am trying to add a new VideoJS object and set it up entirely from JS, without having a DOM video element.
The result is that the video is loaded but there aren't any VideoJS controls.
Here is the code:
obj = document.createElement('video');
$(obj).attr('id', 'example_video_1');
$(obj).attr('class', 'video-js vjs-default-skin');
var source = document.createElement('source');
$(source).attr('src', path);
$(source).attr('type', 'video/mp4');
$(obj).append(source);
$("#content").append(obj);
_V_("example_video_1", {}, function () {
//
}
});
I will appreciate any help, thanks!
Okay took a look at video-js, it's quite nice. Try this:
HTML:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<link href="http://vjs.zencdn.net/c/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/c/video.js"></script>
</head>
<body>
<div id="content"> </div>
<!-- appending video here -->
<hr />
<!-- written in html -->
<video id="example_video_by_hand" class="video-js vjs-default-skin" controls width="640" height="264" poster="http://video-js.zencoder.com/oceans-clip.jpg" preload="auto" data-setup="{}">
<source type="video/mp4" src="http://video-js.zencoder.com/oceans-clip.mp4">
</video>
</body>
</html>
JavaScript:
var obj,
source;
obj = document.createElement('video');
$(obj).attr('id', 'example_video_test');
$(obj).attr('class', 'video-js vjs-default-skin');
$(obj).attr('width', '640');
$(obj).attr('data-height', '264');
$(obj).attr('controls', ' ');
$(obj).attr('poster', 'http://video-js.zencoder.com/oceans-clip.jpg');
$(obj).attr('preload', 'auto');
$(obj).attr('data-setup', '{}');
source = document.createElement('source');
$(source).attr('type', 'video/mp4');
$(source).attr('src', 'http://video-js.zencoder.com/oceans-clip.mp4');
$("#content").append(obj);
$(obj).append(source);
Working example on jsbin.
Updates:
As polarblau pointed out in a comment the jQuery.attr() can take an object rather than having to call jQuery.attr() multiple times like in my first example.
note: The below is just an example and not a working demo.
var attributes = {
'id': 'example_video_test',
'class': 'video-js vjs-default-skin',
'width': '640',
'data-height': '264',
'controls': ' ',
'poster': 'http://video-js.zencoder.com/oceans-clip.jpg',
'preload': 'auto',
'data-setup': '{}'
}
var element = $('<video/>').attr(attributes)
//you would also have to add the source element etc but this gives
//a good example of a shorter approach

Categories

Resources