setPlaybackQuality not changing quality - youtube-iframe-api

I'm trying to change the playback quality of a Youtube video using the iframe/javascript API.
However, the API seems to ignore my request.
Here's a simple example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onPlaybackQualityChange': onPlaybackQualityChange
}
});
}
function changeQuality() {
var qualities = player.getAvailableQualityLevels();
var actual = player.getPlaybackQuality();
for (var i = 0; i < qualities.length; i += 1) {
if (actual !== qualities[i]) {
console.log('Changing quality to:' + qualities[i]);
//onPlaybackQualityChange is never called!
player.setPlaybackQuality(qualities[i]);
break;
}
}
}
function onPlayerReady(event) {
event.target.playVideo();
setTimeout(changeQuality, 1000);
}
function onPlaybackQualityChange(event) {
console.log('Current quality:' + event.data);
}
</script>
</body>
</body>
</html>
If you run the code you can see that onPlaybackQualityChange is only called once the video is loaded and the request to change the video quality using setPlaybackQuality() is completely ignore.
Any help is appreciated. Thanks.

Unfortunately, the setPlaybackQuality() function has not been working for at least a couple of months.
For testing purposes try using setPlaybackRate() and you will find out that you can set the playback rate without any problems, but not the quality.

You have to use setPlaybackQualityRange to set Youtube quality.
Look more info here about setPlaybackQuality https://developers.google.com/youtube/iframe_api_reference#setPlaybackQuality

player.loadVideoById({'videoId': 'M7lc1UVf-VE',
'startSeconds': parseInt(5),
'suggestedQuality': 'hd720'});

Related

How to record video using webcam from all browsers C#

I have a requirement of capturing video with audio from users and upload it to the server. I have worked around with Media Stream recording.
I have adopted the code example from following link.
https://simpl.info/mediarecorder/
I am basically converting the video file to base64 string and upload that to the server. However, this functionality does not support by our friendly safari browser.
The idea is to use any webcam regardless of device such as Windows or Mac computers or even Ipads. I am developing the site using .net technologies.
Any help would be much appreciated. Please note that it could be a similar thread to others but not duplicate one.
As discussed in the comment, I am attaching the code sample code
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Simplest possible examples of HTML, CSS and JavaScript." />
<meta name="author" content="//samdutton.com">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<meta itemprop="name" content="simpl.info: simplest possible examples of HTML, CSS and JavaScript">
<meta itemprop="image" content="/images/icons/icon192.png">
<meta name="mobile-web-app-capable" content="yes">
<meta id="theme-color" name="theme-color" content="#fff">
<base target="_blank">
<title>MediaStream Recording</title>
<link rel="canonical" href="https://simpl.info/mediarecorder" />
<link rel="stylesheet" href="../css/main.css" />
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<div id="container">
<video id="gum" autoplay muted></video>
<video id="recorded" autoplay loop></video>
<div>
<button id="record">Start Recording</button>
<button id="play" disabled>Play</button>
<button id="download" disabled>Download</button>
</div>
</div>
<script src="js/main.js"></script>
<script src="../js/lib/ga.js"></script>
</body>
</html>
Sample JS File
'use strict';
/* globals MediaRecorder */
// This code is adapted from
// https://rawgit.com/Miguelao/demos/master/mediarecorder.html
'use strict';
/* globals MediaRecorder */
// This code is adapted from
// https://rawgit.com/Miguelao/demos/master/mediarecorder.html
var mediaSource = new MediaSource();
mediaSource.addEventListener('sourceopen', handleSourceOpen, false);
var mediaRecorder;
var recordedBlobs;
var sourceBuffer;
var gumVideo = document.querySelector('video#gum');
var recordedVideo = document.querySelector('video#recorded');
var recordButton = document.querySelector('button#record');
var playButton = document.querySelector('button#play');
var downloadButton = document.querySelector('button#download');
recordButton.onclick = toggleRecording;
playButton.onclick = play;
downloadButton.onclick = download;
// window.isSecureContext could be used for Chrome
var isSecureOrigin = location.protocol === 'https:' ||
location.host === 'localhost';
if (!isSecureOrigin) {
alert('getUserMedia() must be run from a secure origin: HTTPS or localhost.' +
'\n\nChanging protocol to HTTPS');
location.protocol = 'HTTPS';
}
// Use old-style gUM to avoid requirement to enable the
// Enable experimental Web Platform features flag in Chrome 49
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var constraints = {
audio: true,
video: true
};
navigator.getUserMedia(constraints, successCallback, errorCallback);
function successCallback(stream) {
console.log('getUserMedia() got stream: ', stream);
window.stream = stream;
if (window.URL) {
gumVideo.src = window.URL.createObjectURL(stream);
} else {
gumVideo.src = stream;
}
}
function errorCallback(error) {
console.log('navigator.getUserMedia error: ', error);
}
// navigator.mediaDevices.getUserMedia(constraints)
// .then(function(stream) {
// console.log('getUserMedia() got stream: ', stream);
// window.stream = stream; // make available to browser console
// if (window.URL) {
// gumVideo.src = window.URL.createObjectURL(stream);
// } else {
// gumVideo.src = stream;
// }
// }).catch(function(error) {
// console.log('navigator.getUserMedia error: ', error);
// });
function handleSourceOpen(event) {
console.log('MediaSource opened');
sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
console.log('Source buffer: ', sourceBuffer);
}
function handleDataAvailable(event) {
if (event.data && event.data.size > 0) {
recordedBlobs.push(event.data);
}
}
function handleStop(event) {
console.log('Recorder stopped: ', event);
}
function toggleRecording() {
if (recordButton.textContent === 'Start Recording') {
startRecording();
} else {
stopRecording();
recordButton.textContent = 'Start Recording';
playButton.disabled = false;
downloadButton.disabled = false;
}
}
// The nested try blocks will be simplified when Chrome 47 moves to Stable
function startRecording() {
var options = {mimeType: 'video/webm', bitsPerSecond: 100000};
recordedBlobs = [];
try {
mediaRecorder = new MediaRecorder(window.stream, options);
} catch (e0) {
console.log('Unable to create MediaRecorder with options Object: ', e0);
try {
options = {mimeType: 'video/webm,codecs=vp9', bitsPerSecond: 100000};
mediaRecorder = new MediaRecorder(window.stream, options);
} catch (e1) {
console.log('Unable to create MediaRecorder with options Object: ', e1);
try {
options = 'video/vp8'; // Chrome 47
mediaRecorder = new MediaRecorder(window.stream, options);
} catch (e2) {
alert('MediaRecorder is not supported by this browser.\n\n' +
'Try Firefox 29 or later, or Chrome 47 or later, with Enable experimental Web Platform features enabled from chrome://flags.');
console.error('Exception while creating MediaRecorder:', e2);
return;
}
}
}
console.log('Created MediaRecorder', mediaRecorder, 'with options', options);
recordButton.textContent = 'Stop Recording';
playButton.disabled = true;
downloadButton.disabled = true;
mediaRecorder.onstop = handleStop;
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(10); // collect 10ms of data
console.log('MediaRecorder started', mediaRecorder);
}
function stopRecording() {
mediaRecorder.stop();
console.log('Recorded Blobs: ', recordedBlobs);
recordedVideo.controls = true;
var base64data;
var superBuffer = new Blob(recordedBlobs, {type: 'video/webm'});
var as =window.URL.createObjectURL(superBuffer);
var reader = new window.FileReader();
reader.readAsDataURL(superBuffer);
reader.onloadend = function() {
base64data = reader.result;
console.log(base64data );
document.write(base64data);
}
}
function play() {
var superBuffer = new Blob(recordedBlobs, {type: 'video/webm'});
recordedVideo.src = window.URL.createObjectURL(superBuffer);
}
function download() {
var blob = new Blob(recordedBlobs, {type: 'video/webm'});
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'test.webm';
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
}
UPDATE
After reading several documents. I finally found a third party plugin to get WebRTC working in Safari and IE which has been provided by Skylink.
Here is the link - https://confluence.temasys.com.sg/display/TWPP
However, this still does not resolve the overall issue of recording the video it shows streaming but does not provide support to save for later use. I really don't want to use Flash as I then have to buy a flash media server. Is there any other way to do this ?
Like, can I host live stream to somewhere and then provide link to watch it later or convert stream to base64string and store that to the database.

Google maps API v3: Can not call method 'lat' of null

I am using Google maps API v3, and this is my HTML file (mylocation.html) :
<!DOCTYPE html>
<html>
<head>
<title>Mylocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
var map;
function initialize() {
var mapOptions = {zoom: 6};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions)n);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
When I open it on the Google Chrome, it works fine, and shows me my location.
In my project, I using WebVew to show this HTML file on Android. But when I run it, in LogCat, I get the following error:
"Uncaught TypeError: Cannot call method 'lat' of null at file:///mnt/sdcard/myloction.html:12"
(I have saved mylocation.html in the SDCard).
I'm not sure how to fix this? Could someone guide me with this?
To access Geolocation in the WebView, you need to do a bit of setup first.
You first must enable the feature in WebSettings: http://developer.android.com/reference/android/webkit/WebSettings.html#setGeolocationEnabled(boolean)
And you must also implement the WebChromeClient.onGeolocationPermissionsShowPrompt:
http://developer.android.com/reference/android/webkit/WebChromeClient.html#onGeolocationPermissionsShowPrompt(java.lang.String, android.webkit.GeolocationPermissions.Callback)
And please also ensure that your application has the appropriate Android permissions to access location.

update markers without reloading the web page google maps v3

First of all I apologize for my poor English but I can not find the answer to my question on all French forums.
I am developing an application that is to make real-time tracking of a fleet of vehicles.
I'm at the end of this application but I have a problem. I can not update my markers without reloading my web page.
I tried with settimeout() but it still charging my map
here is my code thank you for your help.
ps: when completed this application will be available in open source
<html lang="fr">
<head>
<link rel="stylesheet" media="screen" type="text/css" title="Exemple" href="theme.css"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="UTF-8" />
<title>Geonano V1</title>
<style type="text/css">
html{height: 100%}
body{height: 100%; margin: 0px; padding: 0px}
#EmplacementDeMaCarte{height: 100%}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialisation() {
var tableauLieux = [
//here I have a loop in php to get my markers in my database
["Paris", 48.86110, 2.34459],
["Versailles", 48.78199, 2.11045]
];
var optionsCarte = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var maCarte = new google.maps.Map(document.getElementById("EmplacementDeMaCarte"), optionsCarte);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < tableauLieux.length; i++) {
var Lieu = tableauLieux[i];
var pointLieu = new google.maps.LatLng(Lieu[1], Lieu[2]);
bounds.extend(pointLieu);
var marqueurLieu = new google.maps.Marker({
position: pointLieu,
map: maCarte,
title: Lieu[0],
icon : Lieu[3],
clickable: true
});
//création de l'info-bulle
var infoBulle = new google.maps.InfoWindow({
content: Lieu[0]//ici on peut mettre des balises HTML
});
google.maps.event.addListener(marqueurLieu, 'click', function() {
infowindow.setContent(Lieu[i][0]);
infoBulle .open(maCarte,marqueurLieu);
});
}
maCarte.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialisation);
setInterval("initialisation()", 5000);
</script>
</head>
<body>
<div id="EmplacementDeMaCarte"></div>
</body>
<META HTTP-EQUIV="Refresh" CONTENT="120; URL=http://localhost/geonano.php">
</html>
You'll have to request a ressource(may be a PHP-script) which returns the data for the markers(tableauLieux) using AJAX.
Once you got the response, remove the current markers and create the new markers.
If I understand it correctly, you're redrawing the map each 5 second with all the markers.
Bascily what you want to do is store your marker in an array that you can loop through at a later time to change their lat and lng. Clear them from the map, change the information and then put them back on the map. Changing the information is going to need some ajax.
marker.setMap(null);
a good way to do that is using something like
refreshIntervalId = setInterval("requestPoints()", 4000);
function requestPoints() {
$.ajax({
url:'{% url 'gpstracking.ajax.request_tracks' %}',
type: 'get',
dataType: 'json',
data: {
vehicles: vehicles
},
success: function (positions) {
updatePoints (positions);
}
});
}
function updatePoints (positions) {
console.debug('updating markers');
var lttd;
var lgtd;
for (var i=0; i < positions.length; i++) {
lttd = positions[i].latitude;
lgtd = positions[i].longitude;
position = map.createPosition({
lat: lttd,
lng: lgtd,
});
markers[positions[i].registration].setPosition(position);
};
if (positions.length > 1) {
//map.fitZoom();
} else {
map.setCenter (lttd, lgtd);
}
}

google maps api V3 (geolocation)

I am able to run the google maps api to get the geo locations only on the firefox browser. It does not find the geo location on safari and Google crome. It fails stating geolocation service failed. Can some one tell me how I could make this geollocation example run on safari and google crome. I have got this example from google maps api V3
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<link href="http://code.google.com//apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Can some one tell me how I could make this geollocation example run on safari and google crome.
without knowing the versions, perhaps informing the browser to interpret the markup as html5 with
<!DOCTYPE html>
<html>
<head>
....

Google Map V3 API Not working in localhost

I copied following javascript code from google maps documentation, but it doesn't work, it only shows a white blank page, nothing loads.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: http://code.google.com/apis/maps/documentation/javascript/basics.html#SpecifyingSensor
-->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Since v3 require api key what's wrong with it? I checked in google chrome and firefox but no clue.
Looks like you are missing a closing html tag, unless that is a typo.
Add this </html> at the bottom of the page.
You need to provide a center location to create your map. In your initialize() function change the map options to include the location you want to start with:
var myCenter = new google.maps.LatLng(60.0,105.0);
var myOptions = {
zoom: 6,
center: myCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
When (or if) you get a location from the geolocation service the center will be changed by your code.
Old question, will answer anyhow in case anyone else lands here.
I ended up using a slightly different implementation to get this to work:
<script type="text/javascript">
function initialize() {
var mapOptions = {zoom: 8, center: new google.maps.LatLng(-34.397, 150.644)};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp'+
'&key={{API_KEY}}&sensor=false&callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript();
</script>
The part that I had to add to get it to work from other (nearly identical) versions of this, was the () at the end of loadScript(). The implicit function call simply was not happening.
You will need to replace {{API_KEY}} with your own. I am not sure if this is required, but it was part of what led me to a working implementation.
If you do not have one, follow the steps listed here

Resources