YouTube in UIWebView only plays once - objective-c

I have a UIWebView with some YouTube Videos embeded via the iframe code:
<iframe width="190" height="102" src="http://www.youtube.com/embed/...?showinfo=0" frameborder="0" allowfullscreen></iframe>
When it first loads it is possible to view each video exactly once. After viewing it the area is just black with white "Youtube" in it.
Any ideas? Of course reloading the UIWebView after watching a video fixes it, but I don't like this...

I did it! The following Javascript did the job:
<script>
VideoIDs = new Array(...some ids here...);
function getFrameID(id){
var elem = document.getElementById(id);
if (elem) {
if(/^iframe$/i.test(elem.tagName))
return id;
var elems = elem.getElementsByTagName("iframe");
if (!elems.length)
return null;
for (var i=0; i<elems.length; i++) {
if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src))
break;
}
elem = elems[i];
if (elem.id)
return elem.id;
do {
id += "-frame";
} while (document.getElementById(id));
elem.id = id;
return id;
}
return null;
}
var YT_ready = (function(){
var onReady_funcs = [], api_isReady = false;
return function(func, b_before){
if (func === true) {
api_isReady = true;
for (var i=0; i<onReady_funcs.length; i++){
onReady_funcs.shift()();
}
} else if(typeof func == "function") {
if (api_isReady)
func();
else
onReady_funcs[b_before?"unshift":"push"](func);
}
}
})();
function onYouTubePlayerAPIReady() {
YT_ready(true)
}
(function(){
var s = document.createElement("script");
s.src = "http://www.youtube.com/player_api";
var before = document.getElementsByTagName("script")[0];
before.parentNode.insertBefore(s, before);
})();
var players = new Array();
YT_ready(function() {
for(index in VideoIDs) {
var frameID = getFrameID(VideoIDs[index]);
if (frameID) {
players[frameID] = new YT.Player(frameID, {
events: {
"onStateChange": stateChange
}
});
}
}
});
function youtube_parser(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[7].length==11){
return match[7];
}
}
function stateChange(event) {
if(event.data == YT.PlayerState.ENDED){
document.location = 'callback:finished';
document.getElementById(youtube_parser(event.target.getVideoUrl())).contentWindow.location.reload(true);
}
}
</script>

Related

recorded audio distorted in safari 11 when using visualization with web rtc

I've created a demo to show this, it seems that when I show a visualization the recorded audio gets really crunchy. Is there any way I can fix this? This works in chrome and Firefox, but safari is the only offender.
<style>
html, body {
margin: 0!important;
padding: 0!important;
overflow: hidden!important;
width: 100%;
}
</style>
<title>Audio Recording | RecordRTC</title>
<h1>Simple Audio Recording using RecordRTC</h1>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<br>
<button id="btn-start-recording">Start Recording</button>
<button id="btn-stop-recording" disabled>Stop Recording</button>
<label><input id="visualizer" type="checkbox" checked/>Show Visualizer</label>
<hr>
<canvas id="audio-canvas"></canvas>
<div><audio controls autoplay></audio></div>
<script src="https://cdn.webrtc-experiment.com/RecordRTC.js"></script>
<script>
var audio = document.querySelector('audio');
function captureMicrophone(callback) {
if(microphone) {
callback(microphone);
return;
}
if(typeof navigator.mediaDevices === 'undefined' || !navigator.mediaDevices.getUserMedia) {
alert('This browser does not supports WebRTC getUserMedia API.');
if(!!navigator.getUserMedia) {
alert('This browser seems supporting deprecated getUserMedia API.');
}
}
navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: false
}
}).then(function(mic) {
callback(mic);
}).catch(function(error) {
alert('Unable to capture your microphone. Please check console logs.');
console.error(error);
});
}
function replaceAudio(src) {
var newAudio = document.createElement('audio');
newAudio.controls = true;
if(src) {
newAudio.src = src;
}
var parentNode = audio.parentNode;
parentNode.innerHTML = '';
parentNode.appendChild(newAudio);
audio = newAudio;
}
function stopRecordingCallback() {
replaceAudio(URL.createObjectURL(recorder.getBlob()));
btnStartRecording.disabled = false;
setTimeout(function() {
if(!audio.paused) return;
setTimeout(function() {
if(!audio.paused) return;
audio.play();
}, 1000);
audio.play();
}, 300);
audio.play();
if(microphone) {
microphone.stop();
microphone = null;
}
}
var recorder; // globally accessible
var microphone;
var btnStartRecording = document.getElementById('btn-start-recording');
var btnStopRecording = document.getElementById('btn-stop-recording');
var canvas = document.getElementById('audio-canvas');
var visualizerCheckbox = document.getElementById('visualizer');
btnStartRecording.onclick = function() {
this.disabled = true;
this.style.border = '';
this.style.fontSize = '';
if (!microphone) {
captureMicrophone(function(mic) {
microphone = mic;
replaceAudio();
audio.muted = true;
audio.play();
btnStartRecording.disabled = false;
btnStartRecording.style.border = '1px solid red';
btnStartRecording.style.fontSize = '150%';
alert('Please click startRecording button again. First time we tried to access your microphone. Now we will record it.');
});
return;
}
replaceAudio();
audio.muted = true;
audio.play();
if(visualizerCheckbox.checked){
initScope(canvas);
}
var options = {
type: 'audio',
numberOfAudioChannels: 2,
checkForInactiveTracks: true,
bufferSize: 16384,
sampleRate: 48000
};
if(recorder) {
recorder.destroy();
recorder = null;
}
recorder = RecordRTC(microphone, options);
recorder.startRecording();
btnStopRecording.disabled = false;
};
btnStopRecording.onclick = function() {
this.disabled = true;
recorder.stopRecording(stopRecordingCallback);
};
function initScope(audioScopeCanvas) {
if (audioScopeCanvas) {
var analyser;
var mic;
var javascriptNode;
var canvasContext;
audioContext = new AudioContext(); // NEW!!
analyser = audioContext.createAnalyser();
mic = audioContext.createMediaStreamSource(microphone);
javascriptNode = audioContext.createScriptProcessor(2048, 1, 1);
analyser.smoothingTimeConstant = 0.3;
analyser.fftSize = 1024;
mic.connect(analyser);
analyser.connect(javascriptNode);
javascriptNode.connect(audioContext.destination);
//canvasContext = $("#canvas")[0].getContext("2d");
canvasContext = audioScopeCanvas.getContext("2d");
javascriptNode.onaudioprocess = function () {
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
var values = 0;
var length = array.length;
for (var i = 0; i < length; i++) {
values += array[i];
}
var average = values / length;
canvasContext.clearRect(0, 0, 60, 130);
canvasContext.fillStyle = '#00ff00';
canvasContext.fillRect(0, 130 - average, 25, 130);
};
}
}
</script>
you can play with it here:
Http://andrew.colchagoff.com/safari-record.html
I'm using record rtc.

YouTube OnStateChange with multiple players on the same page

I have multiple YouTube players on a single page inside a banner slider and I want to use the YouTube Player API to control them and do other stuff based on the state of the video's. I have the code below which I'm pretty sure of used to work fine where any state changes where registered. But it doesnt work for me anymore. The YouTube object is still there and I can use it to start and stop a video but the onStateChange event never gets triggered. What is wrong with this code?
var YT_ready = (function() {
var onReady_funcs = [],
api_isReady = false;
return function(func, b_before) {
if (func === true) {
api_isReady = true;
for (var i = 0; i < onReady_funcs.length; i++) {
onReady_funcs.shift()();
}
}
else if (typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before ? "unshift" : "push"](func);
}
}
})();
function onYouTubePlayerAPIReady() {
YT_ready(true);
}
var players_homepage = {};
YT_ready(function() {
$("li.video iframe.youtube").each(function(event) {
var frameID_homepage = $(this).attr('id');
if (frameID_homepage) {
players_homepage[frameID_homepage] = new YT.Player(frameID_homepage, {
events: {
'onStateChange': onPlayerStateChange_homepage
}
});
}
});
});
(function(){
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})();
function onPlayerStateChange_homepage(event) {
if (event.data === 0) {
// do something on end
} else if (event.data === 1) {
// do something on play
} else if (event.data === 2) {
// do something on pause
}
}
function pauseVideo_homepage(previousVideo) {
players_homepage[previousVideo].pauseVideo();
}
function playVideo_homepage(currentVideo) {
players_homepage[currentVideo].playVideo();
}

GMaps API - calc route driving into pedestrian area

my calculated route works good so far, but I have some trouble with my destination address.
When the destination is within a pedestrian area (city center), this destination (lat, long) will set to the next valid street. This is probably how it supposed to be, but it's important that I get the route until the specific destination address. What I want: E.g. I drive into the pedestrian area or I drive as far as possible by car and then walk to the destination.
Anyone has an idea how I can solve this problem? I am using the following code, the code works so that is not the problem:
<script type="text/javascript">
var directionsDisplay = new google.maps.DirectionsRenderer({
animation: google.maps.Animation.DROP,
draggable: true
});
var directionsService = new google.maps.DirectionsService();
var map;
var geocoder;
var resultsInput;
var question;
var routeStart, routeEnd;
var travMode;
var frage_gruppen_nr;
var zsf1,zsf2;
var zentrieren;
function initialize() {
geocoder = new google.maps.Geocoder();
routeStart = $('.multiple-short-txt:eq(0) .text:eq(0)');
routeEnd = $('.multiple-short-txt:eq(0) .text:eq(1)');
coords_field_map = $('.text-short:eq(1) .text:eq(0)');
coords_field_map.hide();
zsf1 = $('.multiple-short-txt:eq(1) .text:eq(0)');
zsf2 = $('.multiple-short-txt:eq(1) .text:eq(1)');
var aktuelle_frage = 'r1';
var frage_gruppen_nr = parseInt(aktuelle_frage.substr(1));
frage_gruppen_nr = frage_gruppen_nr - 1;
if(frage_gruppen_nr>1){
routeStart.val('xxxx');
var coords;
var ziel_vorfrage = 'abc';
alert(ziel_vorfrage);
geocoder.geocode( { 'address': ziel_vorfrage}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
});
zentrieren = new google.maps.LatLng(coords);
}else{
zentrieren = new google.maps.LatLng(49.759578, 6.644134);
}
travMode = document.getElementsByTagName("SELECT")[0];
question = '{SGQ}_c';
var mapOptions = {
zoom:12,
center: zentrieren
};
map = new google.maps.Map(document.getElementById('gmap_canvas_'+question), mapOptions);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function(event) {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
if (typeof startLatlng === 'undefined' || !startingPoint.equals(startLatlng)) {
startLatlng = startingPoint;
getLocationName(startingPoint, function(name) {
routeStart.val(name);
});
}
if (typeof endLatlng === 'undefined' || !destination.equals(endLatlng)) {
endLatlng = destination;
getLocationName(destination, function(name) {
routeEnd.val(name);
});
}
//alert('startpoint: '+startingPoint);
calculateDistances(startingPoint, destination);
});
directionsDisplay.setMap(map);
resultsInput = $('.text-long:eq(0) .textarea');
$(resultsInput).attr('readonly', true);
}
function calcRoute() {
var coords;
var coords2;
var start = routeStart.val();
geocoder.geocode( { 'address': start}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
else {
alert('Die Startadresse konnte nicht gefunden werden.');
}
});
var end = routeEnd.val();
geocoder.geocode( { 'address': end}, function(results2, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords2 = String(results2[0].geometry.location)
}
else {
alert('Die Zieladresse konnte nicht gefunden werden.');
}
});
var selectedMode;
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
//
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function calculateDistances(origin, destination) {
var selectedMode;
//select travel mode
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode[selectedMode],
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
$(resultsInput).val('Startaddresse: '+origins[i]+'\n\nReiseziel: '+destinations[j]+'\n\nDistanz: '+results[j].distance.text+'\n\nZeit: '+results[j].duration.text+'');
//save result to fields
zsf1.val(results[j].distance.text);
zsf2.val(results[j].duration.text);
}
}
}
}
function getLocationName(latlng, callback) {
geocoder.geocode({
location: latlng
}, function(result, status) {
if (status === google.maps.GeocoderStatus.OK) {
var i = -1;
console.log(result);
// find the array index of the last object with the locality type
for (var c = 0; c < result.length; c++) {
for (var t = 0; t < result[c].types.length; t++) {
if (result[c].types[t].search('locality') > -1) {
i = c;
}
}
}
var locationName = result[0].formatted_address;
callback(locationName);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

WebRTC + JSEP + Google Channel API - cannot receive remoteStream

I've been trying to get this works, but I don't know what's wrong, can you guys help me? I tried WebRTC code with modification like this.
Both caller and callee enter the web
Web will create channel based on their username
Caller clicks the call button and sends message to spesific channel to some user's username. When caller clicks the call button, he then creates peerConnection and adds localStream
Callee will receive message, and the process goes on like WebRTC sample code. When callee receives an offer, he then creates peerConnection and adds localStream, then creates and sends answer
My code goes like this
var my_username = '{{ current_username }}';
var friend;
var localVideo;
var remoteVideo;
var localStream;
var remoteStream;
var channel;
var channelReady = false;
var pc;
var socket;
var started = false;
// Set up audio and video regardless of what devices are present.
var mediaConstraints = {'mandatory': {
'OfferToReceiveAudio':true,
'OfferToReceiveVideo':true }};
var isVideoMuted = false;
var isAudioMuted = false;
function choiceFriendInitialize() {
var choice_visible = false;
$('ul#friendlist > li').click(function(e) {
$(this).css('background-color', '#808080');
friend = $(this).text();
var choice = $('ul#choice');
choice_visible = true;
choice.css('display', 'inline-block');
choice.css('top', e.pageY);
choice.css('left', e.pageX);
});
// trigger call from here
$('li#call').click(function() {
$('ul#friendlist > li').css('background-color', 'transparent');
$('ul#choice').css('display', 'none');
choice_visible = false;
// call
maybeStart();
doCall();
});
$('li#unfriend').click(function() {
$('ul#friendlist > li').css('background-color', 'transparent');
$('ul#choice').css('display', 'none');
choice_visible = false;
});
$("body").mouseup(function(){
if (choice_visible) {
$('ul#friendlist > li').css('background-color', 'transparent');
$('ul#choice').css('display', 'none');
choice_visible = false;
}
});
}
function initialize() {
console.log("Initializing..");
choiceFriendInitialize();
localVideo = document.getElementById("localVideo");
remoteVideo = document.getElementById("remoteVideo");
openChannel();
doGetUserMedia();
}
function openChannel() {
console.log("Opening channel.");
var channel = new goog.appengine.Channel('{{ token }}');
var handler = {
'onopen': onChannelOpened,
'onmessage': onChannelMessage,
'onerror': onChannelError,
'onclose': onChannelClosed
};
socket = channel.open(handler);
}
function doGetUserMedia() {
// Call into getUserMedia via the polyfill (adapter.js).
var constraints = {"mandatory": {}, "optional": []};
try {
getUserMedia({'audio':true, 'video':constraints}, onUserMediaSuccess, onUserMediaError);
console.log("Requested access to local media with mediaConstraints:\n" + " \"" + JSON.stringify(constraints) + "\"");
} catch (e) {
alert("getUserMedia() failed. Is this a WebRTC capable browser?");
console.log("getUserMedia failed with exception: " + e.message);
}
}
function createPeerConnection() {
var pc_config = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
try {
// Create an RTCPeerConnection via the polyfill (adapter.js).
pc = new RTCPeerConnection(pc_config);
pc.onicecandidate = onIceCandidate;
console.log("Created RTCPeerConnnection with config:\n" + " \"" + JSON.stringify(pc_config) + "\".");
} catch (e) {
console.log("Failed to create PeerConnection, exception: " + e.message);
alert("Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.");
return;
}
pc.onconnecting = onSessionConnecting;
pc.onopen = onSessionOpened;
pc.onaddstream = onRemoteStreamAdded;
pc.onremovestream = onRemoteStreamRemoved;
}
function maybeStart() {
if (!started && localStream && channelReady) {
console.log("Creating PeerConnection.");
createPeerConnection();
console.log("Adding local stream.");
pc.addStream(localStream);
started = true;
// Caller initiates offer to peer.
//if (initiator)
//doCall();
}
}
function doCall() {
console.log("Sending offer to peer.");
pc.createOffer(setLocalAndSendMessage, null, mediaConstraints);
}
function doAnswer() {
console.log("Sending answer to peer.");
pc.createAnswer(setLocalAndSendMessage, null, mediaConstraints);
}
function setLocalAndSendMessage(sessionDescription) {
// Set Opus as the preferred codec in SDP if Opus is present.
sessionDescription.sdp = preferOpus(sessionDescription.sdp);
pc.setLocalDescription(sessionDescription);
sendMessage({from: my_username, to: friend}, sessionDescription);
}
function sendMessage(client, message) {
console.log('C->S: ' + JSON.stringify(message));
var xhr = new XMLHttpRequest();
xhr.open('POST', '/send', true);
xhr.setRequestHeader("Content-type","application/json");
var msgString = {send_info: client, data_message: message};
xhr.send(JSON.stringify(msgString));
}
function processSignalingMessage(message) {
var msg = JSON.parse(message);
var data_message = msg.data_message;
var send_info = msg.send_info;
if (data_message.type === 'offer') {
// Callee creates PeerConnection
if (!started)
maybeStart();
pc.setRemoteDescription(new RTCSessionDescription(data_message));
friend = send_info.from;
doAnswer();
} else if (data_message.type === 'answer' && started) {
pc.setRemoteDescription(new RTCSessionDescription(data_message));
} else if (data_message.type === 'candidate' && started) {
var candidate = new RTCIceCandidate({sdpMLineIndex:data_message.label, candidate:data_message.candidate});
pc.addIceCandidate(candidate);
} else if (data_message.type === 'bye' && started) {
onRemoteHangup();
}
}
function onChannelOpened() {
console.log('Channel opened.');
channelReady = true;
}
function onChannelMessage(message) {
console.log('S->C: ' + message.data);
processSignalingMessage(message.data);
}
function onChannelError() {
console.log('Channel error.');
}
function onChannelClosed() {
console.log('Channel closed.');
}
function onUserMediaSuccess(stream) {
console.log("User has granted access to local media.");
// Call the polyfill wrapper to attach the media stream to this element.
attachMediaStream(localVideo, stream);
localVideo.style.opacity = 1;
localStream = stream;
// Caller creates PeerConnection.
//if (initiator) maybeStart();
}
function onUserMediaError(error) {
console.log("Failed to get access to local media. Error code was " + error.code);
alert("Failed to get access to local media. Error code was " + error.code + ".");
}
function onIceCandidate(event) {
if (event.candidate) {
sendMessage({from: my_username, to: friend}, {type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate});
} else {
console.log("End of candidates.");
}
}
function onSessionConnecting(message) {
console.log("Session connecting.");
}
function onSessionOpened(message) {
console.log("Session opened.");
}
function onRemoteStreamAdded(event) {
console.log("Remote stream added.");
attachMediaStream(remoteVideo, event.stream);
remoteStream = event.stream;
waitForRemoteVideo();
}
function onRemoteStreamRemoved(event) {
console.log("Remote stream removed.");
}
function onHangup() {
console.log("Hanging up.");
transitionToDone();
stop();
// will trigger BYE from server
socket.close();
}
function onRemoteHangup() {
console.log('Session terminated.');
transitionToWaiting();
stop();
}
function stop() {
started = false;
isAudioMuted = false;
isVideoMuted = false;
pc.close();
pc = null;
}
function waitForRemoteVideo() {
if (remoteStream.videoTracks.length === 0 || remoteVideo.currentTime > 0) {
console.log('ada remote stream');
transitionToActive();
} else {
console.log('ga ada remote stream');
setTimeout(waitForRemoteVideo, 100);
}
}
function transitionToActive() {
remoteVideo.style.opacity = 1;
}
function transitionToWaiting() {
remoteVideo.style.opacity = 0;
}
function transitionToDone() {
localVideo.style.opacity = 0;
remoteVideo.style.opacity = 0;
}
function toggleVideoMute() {
if (localStream.videoTracks.length === 0) {
console.log("No local video available.");
return;
}
if (isVideoMuted) {
for (i = 0; i < localStream.videoTracks.length; i++) {
localStream.videoTracks[i].enabled = true;
}
console.log("Video unmuted.");
} else {
for (i = 0; i < localStream.videoTracks.length; i++) {
localStream.videoTracks[i].enabled = false;
}
console.log("Video muted.");
}
isVideoMuted = !isVideoMuted;
}
function toggleAudioMute() {
if (localStream.audioTracks.length === 0) {
console.log("No local audio available.");
return;
}
if (isAudioMuted) {
for (i = 0; i < localStream.audioTracks.length; i++) {
localStream.audioTracks[i].enabled = true;
}
console.log("Audio unmuted.");
} else {
for (i = 0; i < localStream.audioTracks.length; i++){
localStream.audioTracks[i].enabled = false;
}
console.log("Audio muted.");
}
isAudioMuted = !isAudioMuted;
}
setTimeout(initialize, 1);
// Send BYE on refreshing(or leaving) a demo page
// to ensure the room is cleaned for next session.
window.onbeforeunload = function() {
sendMessage({from: my_username, to: friend}, {type: 'bye'});
//Delay 100ms to ensure 'bye' arrives first.
setTimeout(function(){}, 100);
}
// Ctrl-D: toggle audio mute; Ctrl-E: toggle video mute.
// On Mac, Command key is instead of Ctrl.
// Return false to screen out original Chrome shortcuts.
document.onkeydown = function() {
if (navigator.appVersion.indexOf("Mac") != -1) {
if (event.metaKey && event.keyCode === 68) {
toggleAudioMute();
return false;
}
if (event.metaKey && event.keyCode === 69) {
toggleVideoMute();
return false;
}
} else {
if (event.ctrlKey && event.keyCode === 68) {
toggleAudioMute();
return false;
}
if (event.ctrlKey && event.keyCode === 69) {
toggleVideoMute();
return false;
}
}
}
// Set Opus as the default audio codec if it's present.
function preferOpus(sdp) {
var sdpLines = sdp.split('\r\n');
// Search for m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('m=audio') !== -1) {
var mLineIndex = i;
break;
}
}
if (mLineIndex === null)
return sdp;
// If Opus is available, set it as the default in m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('opus/48000') !== -1) {
var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
if (opusPayload)
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
break;
}
}
// Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
return sdp;
}
function extractSdp(sdpLine, pattern) {
var result = sdpLine.match(pattern);
return (result && result.length == 2)? result[1]: null;
}
// Set the selected codec to the first in m line.
function setDefaultCodec(mLine, payload) {
var elements = mLine.split(' ');
var newLine = new Array();
var index = 0;
for (var i = 0; i < elements.length; i++) {
if (index === 3) // Format of media starts from the fourth.
newLine[index++] = payload; // Put target payload to the first.
if (elements[i] !== payload)
newLine[index++] = elements[i];
}
return newLine.join(' ');
}
// Strip CN from sdp before CN constraints is ready.
function removeCN(sdpLines, mLineIndex) {
var mLineElements = sdpLines[mLineIndex].split(' ');
// Scan from end for the convenience of removing an item.
for (var i = sdpLines.length-1; i >= 0; i--) {
var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
if (payload) {
var cnPos = mLineElements.indexOf(payload);
if (cnPos !== -1) {
// Remove CN payload from m line.
mLineElements.splice(cnPos, 1);
}
// Remove CN line in sdp
sdpLines.splice(i, 1);
}
}
sdpLines[mLineIndex] = mLineElements.join(' ');
return sdpLines;
}
When it comes to waitForRemoteVideo, the function calls the else condition. But the blob url for remoteVideo exists.
It's funny that I've been searching for the error and re-writing the code for like three times, and suddenly after posted my question here, I realized my mistake.
Here in the function processSignallingMessage..
if (data_message.type === 'offer') {
// Callee creates PeerConnection
if (!started)
maybeStart();
pc.setRemoteDescription(new RTCSessionDescription(data_message));
friend = send_info.from;
doAnswer();
} else ....
Should be like this:
if (data_message.type === 'offer') {
friend = send_info.from;
// Callee creates PeerConnection
if (!started)
maybeStart();
pc.setRemoteDescription(new RTCSessionDescription(data_message));
doAnswer();
} else ....
because callee need variable friend to be filled before sending candidate message.

google maps api v2 map.removeOverlay() marker array issue

To start off with, I would like to say that I have been looking on the internet for a really long time and have been unable to find the answer, hence my question here.
My latest school project is to create an admin page for adding articles to a database, the articles are connected to a point on a google map. The requirement for adding the point on the map is that the user is able to click the map once and the marker is produced, if the map is clicked a second time the first marker is moved to the second location. (this is what I am struggling with.)
The problem is, as the code is now, I get the error that markersArray is undefined. If I place the var markersArray = new Array; underneath the eventListener then I get an error that there is something wrong the main.js (googles file) and markersArray[0] is undefined in the second if.
By the way, I have to use google maps API v2, even though it is old.
<script type="text/javascript">
//<![CDATA[
var map;
var markers = new Array;
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
if (this.counter == 0) {
if (latlng) {
var marker = new GMarker(latlng);
latlng1 = latlng;
this.map.addOverlay(marker);
this.counter++;
markers.push(marker); //This is where I get the error that markersArray is undefined.
}
}
else if (this.counter == 1) {
if (latlng){
alert (markers[0]);
this.map.removeOverlay(markers[0]);
var markers = [];
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}
I solved the problem. I'm not exactly sure why it worked but this is what it looks like now:
var markersArray = [];
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var type = Articles[i].getAttribute("type");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
var marker = new GMarker(latlng);
if (this.counter == 0) {
if (latlng) {
latlng1 = latlng;
this.map.addOverlay(marker);
markersArray.push(marker);
this.counter++;
}
}
else if (this.counter == 1) {
if (latlng){
this.map.removeOverlay(markersArray[0]);
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}