phonegap - Playing html5 audio from local ressource - javascript

I have build a simple demo app that should play a locally stored mp3-file (delivered as part of the app). I want to use html5-audio instead of phonegap's Media-Object. I am using the howler.js framework to get somewhat better performance.
The local file is stored under www/res/audio/2.mp3.
Everything works fine when running it on my desktop browser. However, I cannot get it to work when deployed to my android device. The weired thing is: The playback of a remotely hosted mp3-file works just peachy, thus I assume that something is wrong with url(s) I use with my local file. I have tried different url-"versions", but none of the below works:
www/res/audio/2.mp3
/android_asset/www/res/audio/2.mp3
file:///android_asset/www/res/audio/2.mp3
file://android_asset/www/res/audio/2.mp3
http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3 //works great
It drives me crazy. Any ideas how to get it to work and what my mistake is? Please see my code below or download my entire code here.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/jquery.mobile-1.4.3.min.css" />
<title>Audio-Test</title>
</head>
<body>
<!-- ------------- -->
<!-- Script import -->
<script src="js/libs/jquery-2.1.1.min.js"></script>
<script src="js/libs/jquery.mobile-1.4.3.min.js"></script>
<script src="js/libs/howler/howler.min.js"></script>
<script src="js/index.js"></script>
<!-- ---------- -->
<!-- Start Page -->
<div id="index" data-role="page" data-theme="a">
<!-- HEADER, FOOTER -->
<div data-role="header" data-position="fixed">
<h1>Audio-Tester</h1>
</div>
<!-- CONTENT -->
<div class="ui-content">
<h1 id='ready' style='text-align: center;'></h1>
<select id='urls'></select>
<button id='playSelected'>Play audio from selected source!</button>
<div id='log'></div>
</div>
</div>
<!-- ------------- -->
<!-- Init Phonegap -->
<script>
$(document).ready(function() {
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
isPhonegap = true;
$.getScript( 'cordova.js', function() {
document.addEventListener("deviceready", onDeviceReady, false);
app.initialize();
});
}
else {
//Fallback for desktop browsers!
isPhonegap = false;
onDeviceReady();
}
});
</script>
</body>
</html>
index.js
function onDeviceReady() {
$('#ready').html("I'm ready!");
//populate selection
var basePath = getBasePath();
var audioUrl = 'res/audio/2.mp3';
var myOptions = {
val1 : 'http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3',
val2 : audioUrl,
val3 : basePath + audioUrl,
val4 : 'file://' + basePath + audioUrl,
val5 : 'file:/' + basePath + audioUrl
};
var urls = $('#urls');
$.each(myOptions, function(val, text) {
urls.append(
$('<option></option>').val(val).html(text)
);
});
//append listener to button
$('#playSelected').click(function() {
var myHowl = new Howl({ urls: [$('#urls option:selected').text()] });
myHowl.play();
$('#log').html($('#log').html() + '<br /> Playing ' + myHowl.urls());
});
}
function getBasePath() {
var htmlFilename = 'index.html';
var path = window.location.pathname;
path = path.substr(0, path.length - htmlFilename.length);
return path;
}

This code is working in phonegap.
<body>
<audio controls>
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>

$('#playSelected').click(function() {
var media = new Media(your_audioUrl);
media.play();
}

Related

CEFSharp "Uncaught ReferenceError: method is not defined\n# about:blank:1:0"

I am using CEFSharp in WPF app.
Currently i am loading local html file in chromium based browser.
xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Name="buttonTest" Content="Click me" Grid.Row="0" Width="50px" Height="30px" Click="buttonTest_Click" />
<!--<WebBrowser Name="webBrowser" Grid.Row="1" />-->
<!--<WebBrowser Name="webBrowser" Grid.Row="1" />-->
<wpf:ChromiumWebBrowser x:Name="webBrowser" Grid.Row="1"/>
</Grid>
cs
BrowserSettings browserSettings = new BrowserSettings();
browserSettings.FileAccessFromFileUrls = CefState.Enabled;
browserSettings.Javascript = CefState.Enabled;
browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
webBrowser.BrowserSettings = browserSettings;
webBrowser.Address = "file:///" + path;
Loading html is working completely fine.
Now i am trying to call javascript function on a click of WPF Button.
private async void buttonTest_Click(object sender, RoutedEventArgs e)
{
try
{
if (webBrowser.IsBrowserInitialized)
{
var task = await webBrowser.EvaluateScriptAsync("document.body.style.background = 'red';");
var task1 = await webBrowser.EvaluateScriptAsync("startInterval()", new Object { });
//webBrowser.ExecuteScriptAsync("alert(2 + 2);");
}
//webBrowser.InvokeScript("startInterval");
}
catch (Exception ex)
{
}
}
html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/site.css" />
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/site.js"></script>
<script type="text/javascript">
$(function () {
'use strict';
function startInterval() {
alert("qqf5");
}
function clearInterval() {
}
$("#buttonGetData").click(function () {
startInterval();
});
});
</script>
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
<button type="button" id="buttonGetData">Get Data!</button>
</main>
</div>
</body>
</html>
From wpf if i click on button then page background color is changed but method is not called.
But if i click on from html page then it it working fine.
What i am missing here?

Getting a loading scren to work with Polymer

I'm trying to get a loading screen to work in Polymer, as seen in this Gist: https://gist.github.com/SlicedSilver/f2e93a5995f84d9cd512
The idea's pretty simple: the entrypoint is a lightweight HTML file that renders the loading screen, whose body contains an onload callback that loads up the Polymer app via the DOM once that lightweight page is rendered.
It works beautifully on desktop browsers. On mobile browsers the filestoload.html is never getting loaded (but also isn't throwing any errors), so the loading screen just stays there and the app never loads. The full code is below, but particular attention goes to this line:
tag.setAttribute('onload', 'polymerLoader.insertPolymerApplication()');
That onload event never fires and never throws an error. I've tried catching it both through the DOM and with a proper event hander to no avail. I've even tried taking it out of the hands of the JS altogether as a sanity check, adding the link to the HTML file like so:
<link rel="import" href="/filestoload.html" onload="polymerLoader.insertPolymerApplication()" >
Same result - displays the app on desktop, but just shows the loading screen on mobile. I'm fresh out of ideas. Any help?
....
Here's the lightweight entry point (index.html)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<link rel="shortcut icon" type="image/png" href="/assets/images/favicon.ico"/>
<title>GreenMaven</title>
<meta name="description" content="greenmaven description">
<script src="assets/js/polymerAppLoader.js"></script>
<style type="text/css">
.loading {
position: fixed;
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
z-index: -500;
display: block;
}
</style>
</head>
<body onload="polymerLoader.loadPolymerApplication()">
<div id="loader" class="loading">
<img src="assets/images/gears.svg" />
</div>
</body>
</html>
And here's the JS that loads the rest of the Polymer app:
'use strict';
/* global polymerLoader */
/*jshint unused:false*/
/*jshint -W079*/
// This is the normal conditional loader for the Web components Polyfill
if ('registerElement' in document && 'createShadowRoot' in HTMLElement.prototype && 'import' in document.createElement('link') && 'content' in document.createElement('template')) {
// We're using a browser with native WC support!
} else {
// Add web components polyfill...
document.write('<script src="bower_components/webcomponentsjs/webcomponents.lite.js"><\/script>');
}
var polymerLoader = (function() {
// Function for creating a link element and inserting it into the <head> of the html document
function addLinkTag(elementType, address, shim, loadTrigger) {
var tag = document.createElement('link');
tag.rel = elementType;
tag.href = address;
if (shim) {
// add the shim-shadowdom attribute
tag.setAttribute('shim-shadowdom', '');
}
if (loadTrigger) {
// This file needs to be loaded before inserting the Polymer Application
// when finished loading it will call the polymerLoader.insertPolymerApplication() function
tag.setAttribute('onload', 'polymerLoader.insertPolymerApplication()');
expectedCalls++;
}
document.getElementsByTagName('head')[0].appendChild(tag);
}
var pgApploaded = false;
function loadPolymerApplication() {
// Only insert once.
if (!pgApploaded) {
addLinkTag('import', 'filestoload.html', false, true);
pgApploaded = true;
}
}
// Counter variable for insertPolymerApplication() calls
var callCount = 0;
var expectedCalls = 0;
function insertPolymerApplication() {
callCount++;
// Only when callCount >= expectedCalls
// The application is only inserted after all required files have loaded
// for the application to work.
if (callCount >= expectedCalls) {
// here is the html that is inserted when everything is loaded.
document.querySelector('body').innerHTML += '<template is="auto-binding" id="app"><polymer-app id="main-app"></polymer-app></template>';
document.getElementById('loader').style.display = 'none';
}
}
return {
insertPolymerApplication: function() {
insertPolymerApplication();
},
loadPolymerApplication: function() {
loadPolymerApplication();
}
};
})(document);
And finally, here's the filestoload.html file that has the links and scripts that would usually be found in the Polymer index.html:
<!doctype html>
<!-- Here is where you put the scripts required by the page, that would normally be -->
<!-- included in the index.html page, you can still use grunt/gulp build functions on these -->
<!-- will be replaced with elements/elements.vulcanized.html -->
<link rel="manifest" href="/manifest.json">
<link rel="import" href="/src/greenmaven-app/greenmaven-app.html">
<link rel="stylesheet" href="assets/css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<!-- endreplace-->
<!-- build:js scripts/app.js -->
<script src="properties_base/farmhacker-properties.js"></script>
<!-- endbuild-->
<!-- build:js scripts/thirdparty.js -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script>
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - $('#navbar').height()
}, 1000);
return false;
}
}
});
});
</script>
<!-- endbuild-->
Turns out to be some kind of bug in the Polymer build, probably related to another error where running polymer build was resulting in the app throwing a bunch of 404 errors from bower components.
When I did a raw deployment (without building/vulcanizing) to the server, everything worked fine on both desktop and mobile, and without the errors.

UWP BTLE: Cannot read device advertisements

I am new to this UWP, so bear with me please. I modified the code in the following MS GitHub: Link to create a Windows Phone App that can 'watch' BTLE advertisements.
But it is not able to read it any advertisements. My phone does support BTLE, I am able to see the devices in Windows BT Settings so the device is advertising it too. Please help me find where I am wrong and why.
Here is my code for JS:
var watcher = new Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher();
//watcher.signalStrengthFilter.inRangeThresholdInDBm = -70;
//watcher.signalStrengthFilter.outOfRangeThresholdInDBm = -75;
//watcher.signalStrengthFilter.outOfRangeTimeout = 2000;
$(document).ready(function () {
console.log("HERE: ready");
watcher.onreceived = onAdvertisementReceived;
$("button#start").unbind('click').on('click', function (e) {
console.log('CLICKED >');
e.preventDefault();
watcher.start();
});
$("button#stop").unbind('click').on('click', function (e) {
console.log('CLICKED <');
e.preventDefault();
watcher.stop();
});
});
function onAdvertisementReceived(eventArgs) {
console.log("HERE: function watcher", eventArgs);
var timestamp = eventArgs.timestamp;
var advertisementType = eventArgs.advertisementType;
var rssi = eventArgs.rawSignalStrengthInDBm;
var localName = eventArgs.advertisement.localName;
$("div#list > ul").append("<li> Timestamp: <strong>" + timestamp.getHours() + ":" + timestamp.getMinutes() +
":" + timestamp.getSeconds() + "</strong> Type:" + advertisementType.toString() + " RSSI:" + rssi.toString() + " Name:" +
localName + "</li>");
}
Here is my HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Bluetooth LE Smart Watch</title>
<link href="css/default.css" rel="stylesheet" />
<link href="css/materialize.min.css" rel="stylesheet" />
</head>
<body class="container">
<div class="row">
<h4>List of BTLE Devices</h4>
<button class="btn" id="start">Start Watcher</button><button class="btn" id="stop">Stop Watcher</button>
<div id="list" class="col m12 s12">
<ul>
</ul>
</div>
</div>
<script src="js/jquery-2.2.4.min.js"></script>
<script src="js/materialize.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
But it is not able to read it any advertisements. My phone does support BTLE, I am able to see the devices in Windows BT Settings so the device is advertising it too. Please help me find where I am wrong and why.
To get the BTLE work, you need to enable the BlueTooth capability in package.appxmannifest. You can achieve this through:
In VS2015->Double click package.appxmannifest->Capabilities->Check Bluetooth capability.
Or You can open package.appxmannifest in code view and add <DeviceCapability Name="bluetooth" /> in Capabilities tag:
<Capabilities>
<Capability Name="internetClient" />
<DeviceCapability Name="bluetooth" />
</Capabilities>

Javascript Function works inside HTML page but doesn't work from external .js file

I am trying to place some Javascript code inside a .js file so that I can call it from multiple HTML pages. The problem is, my Javascript code works fine if I place it in a script within the HTML page, but when placed in a external .js file, it simply does not work. I've looked at these questions quite a few times and still cannot find the error.
Here's the HTML page:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<link rel="stylesheet" type="text/css" href="css/contacts.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src ="js/contactsModule.js"></script>
<title>Hall of Heroes</title>
</head>
<body onload = "contactsModule.getContacts();">
<!-- Global Header Starts Here -->
<div class="header">
<div class="cancel">
<img src="img/cancel.png" /><!-- if screen is triggered from onboarding, then go back to onboarding screen instead of home -->
</div>
<h1>My Contacts</h1>
</div>
<div class="wrapper">
<h3>A</h3> <!-- letter header goes here -->
<!-- Begin Contact Unit -->
<div class="feed">
</div>
<!-- End Contact Unit -->
</div>
</body>
</html>
And here is the .js file:
var contactsModule = (function($){
function getContacts()
{
dbContacts();
}
function displayContacts(contactArray){
window.alert('displayContacts now running!');
var jsonObject = $.parseJSON(contactArray);
jsonObject.forEach(function (dat) {
//Begin Contact Unit
$('.feed')
.append('<div class="feed-img"><img src="' + dat.avatarUrl + '"/>\
</div><div class="feed-text"><p><span class="name_highlight">\
' + dat.firstName + ' ' + dat.lastName + '</span></p></div>');
//End Contact Unit
});
}
function dbContacts() {
var avatarUrl;
var firstName;
var lastName;
$.ajax({
type: "GET",
url: "http://www.hallofheroesapp.com/php/contacts.php",
data: {avatarUrl: avatarUrl, firstName: firstName, lastName: lastName},
success: function (response) {
window.alert('AJAX ran successfully!');
displayContacts(response);
},
error: function(response){
alert("Error:" + response);
}
});
}
}(jQuery));
Thank you for your help!
You aren't returning anything from your IIFE. contactsModule will then not contain anything, ie equal undefined. Also just defining functions doesn't make those functions part of some object, with the exception of globally defined functions. You have to assign them, or define them as part of an object literal
Your code should be something like
var contactsModule = (function($){
return {
getContacts: function() {
/* code */
},
displayContacts: function(contactArray){
/* code */
}
dbContacts function() {
/* code */
}
};
}(jQuery));
How about using
$(document).ready(function(){
///// your code here...
});
... change ...
<body onload = "contactsModule.getContacts();">
... to ...
<body>
... and add event handler using jquery ...
(function($){
function getContacts()
{
dbContacts();
}
/* ... etc ... */
// use jquery's onready handler
$(getContacts);
}(jQuery));
Had the same problem. Easy thing when you research on google.
Your Js code loads before the DOM loads. Which should be the other way around. So you have to use this
$(document).ready(function(){
//only jQuery is recommended, global JavaScript functions outside!
});
Also JavaScript
document.addEventListener("DOMContentLoaded", function(event) {
//global function outside!
});
Only this way you can be sure that your DOM is loaded before your jquery finds your elements.

x-ms-webview is not displaying properly in windows phone 8.1 javascript app

I am developing a wp8.1 app in javascript. The x-ms-webview is being displayed in a very small size.
Screenshot:
https://flic.kr/p/oi2WNm
default.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Miley_Cyrus_Tweets.WindowsPhone</title>
<!-- WinJS references -->
<!-- At runtime, ui-themed.css resolves to ui-themed.light.css or ui-themed.dark.css
based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
<link href="/css/ui-themed.css" rel="stylesheet" />
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- Miley_Cyrus_Tweets.Phone references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body class="phone">
<center>
<br /><br />
<x-ms-webview id="webview" src="ms-appx-web:///page.html" width="400" height="600"></x-ms-webview>
</center>
</body>
</html>
default.css
body {
background-color: #ffffff;
}
Here's what I've tried to make it bigger:
Increasing width and height values of x-ms-webview in default.html
Using zoom: 200%; for body in default.css
In both cases, the x-ms-webview became larger but also shifted toward right.
So, my question is:
What do I need to do to make it bigger while keeping it center-aligned?
perhaps these code will help you.
it comes from cordova inappbrowser.
if (!browserWrap) {
browserWrap = document.createElement("div");
browserWrap.style.position = "absolute";
browserWrap.style.borderWidth = "0";
browserWrap.style.width = "100%";
browserWrap.style.height = "100%";
browserWrap.style.borderStyle = "solid";
browserWrap.style.borderColor = "rgba(0,0,0,0.25)";
browserWrap.style.zIndex = 100000;
document.body.appendChild(browserWrap);
}
popup = document.createElement(isWebViewAvailable ? "x-ms-webview" : "iframe");
popup.style.borderWidth = "0";
popup.style.width = "100%";
popup.style.height = "100%";
popup.src = strUrl;
browserWrap.appendChild(popup);

Categories