Playing WebAudio API automatically in iOS 6 - html

I was performing some tests with the WebAudio API in iOS6. It seems that when you click on a button, the AudioBufferSourceNode will be created correctly and connected to the Contexts destination.
I was simply wondering if there was any way of playing a sound automatically when a page is loaded, as iOS6 devices seem to build the SourceNode correctly, but no sound comes out.
I have posted my code below:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML 5 WebAudio API Tests</title>
<script type="text/javascript">
var audioContext,
audioBuffer;
function init() {
try {
audioContext = new webkitAudioContext();
initBuffer('resources/dogBarking.mp3');
} catch(e) {
console.error('webkitAudioContext is not supported in this browser');
}
}
function initBuffer(desiredUrl) {
var url = desiredUrl || '';
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
audioBuffer = buffer;
}, onError);
}
request.send();
}
function playSound(startTime, endTime) {
var audioSource = audioContext.createBufferSource();
audioSource.buffer = audioBuffer;
audioSource.connect(audioContext.destination);
audioSource.noteOn(0);
audioSource.noteOff(10);
}
</script>
</head>
<body onload="init()">
<script type="text/javascript">
(function() {
var buttonNode = document.createElement('input');
buttonNode.setAttribute('type', 'button');
buttonNode.setAttribute('name', 'playButton');
buttonNode.setAttribute('onclick', 'playSound(0, 1)')
buttonNode.setAttribute('value', 'playSound()');
document.body.appendChild(buttonNode);
document.write('<a id="test" onclick="playSound(0, 2)">hello</a>');
var testLink = document.getElementById('test');
var dispatch = document.createEvent('HTMLEvents');
dispatch.initEvent("click", true, true);
testLink.dispatchEvent(dispatch);
}());
</script>
</body>
</html>
I hope this makes sense.
Kind regards,
Jamie.

This question is very similar to No sound on iOS 6 Web Audio API . WebAudio API needs user input to be initialized and after first sound plays in this way WebAudioAPI works greatly without any actions needed during current session.
You can initialize API by adding listener to first window touchstart event, like this:
w.addEventListener('touchstart', myFunctionThatPlaysAnyWebAudioSound);

Related

Here maps not draggable in ms access webbrowser

I have created a simple html using the draggable marker example from here maps. I have adapted it to support IE 11 by adding reference to legacy js, meta tag and using P2D engine in map options. Also added two url parameters for coordinates. It works perfectly in IE11 and it loads and shows pan and zoom buttons in ms-access webbrowser but it keeps static, it's not draggable, but pan and zoom works.
The curious thing is that if I navigate to wego.here.com in the same webbrowser control then the map is draggable. So they're doing something else in the here maps main page that I'm not doing in my script.
I have also tried using Microsoft Web Browser from the activex controls list in access.
I need it to be draggable so I can pick the coordinates after the user changes the marker position.
This is my script:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Draggable Marker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
<style>
html, body { margin:0px; padding:0px; width: 100%; height: 100%; }
.main { height: 100%; }
</style>
</head>
<body id="markers-on-the-map">
<div class="main" style="width:100%" id="map"></div>
<input type="hidden" id="long" name="long">
<input type="hidden" id="lat" name="lat">
<script>
function addDraggableMarker(map, behavior){
var marker = new H.map.Marker({lat:latitud, lng:longitud}, {volatility: true});
// Ensure that the marker can receive drag events
marker.draggable = true;
map.addObject(marker);
// disable the default draggability of the underlying map
// and calculate the offset between mouse and target's position
// when starting to drag a marker object:
map.addEventListener('dragstart', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
var targetPosition = map.geoToScreen(target.getGeometry());
target['offset'] = new H.math.Point(pointer.viewportX - targetPosition.x, pointer.viewportY - targetPosition.y);
behavior.disable();
}
}, false);
// re-enable the default draggability of the underlying map
// when dragging has completed
map.addEventListener('dragend', function(ev) {
var target = ev.target;
if (target instanceof H.map.Marker) {
$('#long').val(ev.target.b.lng);
$('#lat').val(ev.target.b.lat);
behavior.enable();
}
}, false);
// Listen to the drag event and move the position of the marker
// as necessary
map.addEventListener('drag', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
target.setGeometry(map.screenToGeo(pointer.viewportX - target['offset'].x, pointer.viewportY - target['offset'].y));
}
}, false);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: '?????????????????????????????????'
});
var defaultLayers = platform.createDefaultLayers();
//url parameters
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
var latitud=query_string.lat;
var longitud=query_string.long;
//Step 2: initialize a map - this map is centered over Boston
var map = new H.Map(document.getElementById('map'),
defaultLayers.raster.normal.map, {
center: {lat:latitud, lng:longitud},
engineType: H.map.render.RenderEngine.EngineType.P2D,
zoom: 12,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
//window.addEventListener('resize', () => map.getViewPort().resize());
window.addEventListener('resize', function () {map.getViewPort().resize(); });
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
//var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: Create the default UI:
var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US');
// Add the click event listener.
addDraggableMarker(map, behavior);
</script>
</body>
</html>```
Check please on this static page
: your code works for my IE11

Microphone Audio Visualizer Web Audio API

I am new in Canvas of HTML5. What I want to do. I want a microphone audio visualizer just like windows Sound visualizer of microphone (control panel => hardware and sound => Sound => recording)
Can anybody tell me Please how I will create it in canvas and adjust with web audio API ?
An other problem is My visualizer is more sensitive. How i will adjust it. I want blank spectrum if no sound is there.
I am sharing a picture what I exactly want.
Img url: http://phillihp.com/wp-content/uploads/2011/12/winamp-step-pre-step-1.png
Please help me out to solve this problem.
Untitled Document
<body>
<canvas id="test"></canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
navigator.webkitGetUserMedia({audio:true}, function(stream){
audioContext = new AudioContext();
analyser = audioContext.createAnalyser();
microphone = audioContext.createMediaStreamSource(stream);
javascriptNode = audioContext.createScriptProcessor(1024, 1, 1);
analyser.smoothingTimeConstant = 0.0;
analyser.fftSize = 512;
microphone.connect(analyser);
analyser.connect(javascriptNode);
javascriptNode.connect(audioContext.destination);
//canvasContext = $("#canvas")[0].getContext("2d");
canvasContext = document.getElementById("test");
canvasContext= canvasContext.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, 150, 300);
canvasContext.fillStyle = '#00ff00';
canvasContext.fillRect(0,130-average,25,140);
}
}, function(e){ console.log(e); }
);
</script>
</body>
Check out this code sample: https://github.com/cwilso/volume-meter/.
Based on cwilso answer. Fixed the problem with mobile devices. "StartNow" is the main JS function in main.js (originallt called by window.onload):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Volume Meter</title>
<script src="volume-meter.js"></script>
<script src="main.js"></script>
</head>
<body onload="javascript:StartNow()"> >
<p>uses audioContext.createScriptProcessor(buffer size) Web Audio API. Use https://webaudio.github.io/web-audio-api/#audioworklet</p>
<canvas id="meter" width="1100" height="60"></canvas>
<p>On Android press button to start (fixes new security requirement added in the new Android OS version)</p>
<button onclick="javascript:StartNow()">Start</button>
</body>
</html>
On Android you need to press the button to start.
This is necessary because of a NEW security requirement added in the new Android OS.

HTML5 getUserMedia() media sources

I have created a streaming webcam with html5. At the moment I can take a picture through my web cam, but I would like to know if it is possible to choose media stream device from the list, e.g. I have two web cams I want to choose the webcam to activate. How can I do that with html5 getUserMedia() call?
Thanks!
You can get the list of web camera
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Video Camera List</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js" ></script>
<style type="text/css" media="screen">
video {
border:1px solid gray;
}
</style>
</head>
<body>
<script>
if (!MediaStreamTrack) document.body.innerHTML = '<h1>Incompatible Browser Detected. Try <strong style="color:red;">Chrome Canary</strong> instead.</h1>';
var videoSources = [];
MediaStreamTrack.getSources(function(media_sources) {
console.log(media_sources);
// alert('media_sources : '+media_sources);
media_sources.forEach(function(media_source){
if (media_source.kind === 'video') {
videoSources.push(media_source);
}
});
getMediaSource(videoSources);
});
var get_and_show_media = function(id) {
var constraints = {};
constraints.video = {
optional: [{ sourceId: id}]
};
navigator.webkitGetUserMedia(constraints, function(stream) {
console.log('webkitGetUserMedia');
console.log(constraints);
console.log(stream);
var mediaElement = document.createElement('video');
mediaElement.src = window.URL.createObjectURL(stream);
document.body.appendChild(mediaElement);
mediaElement.controls = true;
mediaElement.play();
}, function (e)
{
// alert('Hii');
document.body.appendChild(document.createElement('hr'));
var strong = document.createElement('strong');
strong.innerHTML = JSON.stringify(e);
alert('strong.innerHTML : '+strong.innerHTML);
document.body.appendChild(strong);
});
};
var getMediaSource = function(media) {
console.log(media);
media.forEach(function(media_source) {
if (!media_source) return;
if (media_source.kind === 'video')
{
// add buttons for each media item
var button = $('<input/>', {id: media_source.id, value:media_source.id, type:'submit'});
$("body").append(button);
// show video on click
$(document).on("click", "#"+media_source.id, function(e){
console.log(e);
console.log(media_source.id);
get_and_show_media(media_source.id);
});
}
});
}
</script>
</body>
</html>
In the latest Chrome Canary (30.0.1587.2) it looks like you can enable device enumeration in chrome://flags (looks like it might already be enabled) and use the MediaStreamTrack.getSources API to select the camera.
See this WebRTC bug and mailing list post for more details.

Drag n' drop text file

I want dropped text files to be shown by their contents or their complete location so that I can load contents of that location into the "drop_zone".
This is what I have till now. I was just able to access the file name:
<html>
<head>
<title></title>
</head>
<body>
<textarea id="drop_zone">Drop files here</textarea>
<output id="list"></output>
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
document.getElementById('drop_zone').innerHTML = files[0].name;
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
</body>
</html>
here is the final code :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="drop_zone">Drop files here</textarea>
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
var reader = new FileReader();
reader.onload = function(event) {
document.getElementById('drop_zone').value = event.target.result;
}
reader.readAsText(files[0],"UTF-8");
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
</body>
</html>
http://www.html5rocks.com/en/tutorials/file/dndfiles/ should be a good resource. You need to use a FileReader to read the contents of the file as a String.
Due to security limits, a page isn't able to load contents of files without something like a Java applet set up with appropriate permissions; and, even then, it's not too possible.
However, that isn't to say it's impossible; simply upload the file to a server and echo the contents back out to the browser. That is how many text-editing-type web applications function.
How you implement this is up to you.
Further, as Maz has pointed out, you can also use built-in APIs to aid you in doing what you're trying to do. Do note, however, this solution is not necessarily cross-browser compatible.

How do I display the location of the user on a Google Map in HTML5?

I'm trying to put a Google map in my page and make it so that when the page loads the map will display exactly the location of the user. In order to do so, I've taken the google maps API code and inserted it into my HTML5 page. At first the browser did ask for permission to share my location but it isn't actually showing this location on the map; I've tried with two or more combinations of functions but it is still not working.... please, I need help! If anyone can tell me what is wrong with the code please do:
<html lang="en" manifest="halma.manifest">
<head>
<meta charset="utf-8">
<title>helmas</title>
<link rel="stylesheet" type="text/css" href="css2.css">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAycdS3aS7dItIegOaJzT2RBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSiGkO1l1KdZvNzo-8b-o7M21o4UA"></script>
<!--[if IE]>
<script src="excanvas.js"></script>
<![endif]-->
</head>
<<body onload="loadMap()" onunload="GUnload()">
<article>
<div id="map" style="width:100%;height:800px;"></div>
<script>
if (navigator.geolocation) {
// try to get the users location
}
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.watchPosition(showPositionOnMap, errorMessage,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 });
}
else {
alert("Geolocation is not supported by this browser");
}
var map = null;
function loadMap() {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(52.2021, 0.1346 ), 12); // (sets the map centre to Cambridge UK)
map.setUIToDefault();
}
function showPositionOnMap(position) {
var geoCoords = new GLatLng(position.coords.latitude, position.coords.longitude);
map.addOverlay(new GMarker(geoCoords));
}
function errorMessage(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
</script>
Perhaps the sensor parameter in the maps invocation needs to be set to "true" - at the moment you have it set to "false". So your script tag should contain this url
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAycdS3aS7dItIegOaJzT2RBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSiGkO1l1KdZvNzo-8b-o7M21o4UA"></script>
For more info:
Google Maps Api sensor location