How to add sounds with JQM and IntelXDK - android

I am working on an app and using IntelXDK to build it. I need to play some sounds if conditions are met, first I have tried HTML5 with JS and on desketop it's working but when built, it has no sound...
First attempt - HTML5 & JS
<audio src="snd/yes.mp3" id="yes"></audio>
<audio src="snd/no.mp3" id="no"></audio>
if(condition) {
$('#yes').trigger("play");
} else {
$('#no').trigger("play");
}
Then I tried the native IntelXDK version that goes like this:
if(condition) {
intel.xdk.player.playSound("snd/yes.mp3");
} else {
intel.xdk.player.playSound("snd/no.mp3");
}
No only that it doesn't work but it also f***s up the rest of my code not allowing the popup and page change to trigger.
Does anyone know how to fix this ?
Do I need to preload the sounds before playing them?
**UPDATE
I just discovered that if I use the HTML5 Audio tags and I give links to the sounds inside my server, the sounds are working, but if I try to get the same sounds from my snd folder they won't work...why is that?

The problem is that your "root" is not where you think it is, so your "snd" directory is not being found. This problem varies, unfortunately, with each target, it is not something the XDK controls, it has to do with how Cordova apps are constructed. You can use these functions to locate the root of your files and that should help you make this work.
// getWebPath() returns the location of index.html
// getWebRoot() returns URI pointing to index.html
function getWebPath() {
"use strict" ;
var path = window.location.pathname ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return 'file://' + path ;
}
function getWebRoot() {
"use strict" ;
var path = window.location.href ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return path ;
}

Related

XMLHttpRequest in Cordova for android

I'm actually stuck with a problem. Building a app in Cordova, for Android. I need to download a PDF from a variable path in the server. With a documentation from Cordova said "Transition off of cordova-plugin-file-transfer", located here , I tried this:
var oReq = new XMLHttpRequest();
// Make sure you add the domain name to the Content-Security-Policy <meta> element.
oReq.open("GET", endereco, true);
// Define how you want the XHR data to come back
oReq.responseType = "blob";
oReq.onload = function (oEvent) {
var blob = oReq.response; // Note: not oReq.responseText
if (blob) {
console.log("WORKS??");
} else console.error('we didnt get an XHR response!');
};
oReq.send(null);
where "endereco" is a variable where I store the pdf path. So, I'm testing and testing, but maybe someone got some pointers in how to implement this. Right now it just log "WORKS??", so I actually connected successfully. But what now?
1 - so, I made a request, but the file was saved? Couldn't find nothing in my mobile. How can I save said blob in a folder, with the same name and extension from the server?
So, if someone can at least send me to some proper examples or documentation, it would help a lot. Right now I'm reading all on MDN Web Docs, but I'm fairly noob with this type of code :(
thanks in advance!
so, this is how it worked for me! Using the info from the official documentation at cordova, formerly named "cordova-plugin-file" (link), and the amazing info from this page with examples "CORDOVA FILE PLUGIN EXAMPLES" (link) it worked. It could use some cleanup and some error callbacks, but right now I can run this, and download and save an pdf to my android. Hope it helps someone! B-)
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
var fileURL;
var req = new XMLHttpRequest();
req.open("GET", endereco, true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
console.log(blob.type);
console.log("WORKS!");
console.log(fileURL);
// cordova.file.etc is where you will save the file. In this case, inside the app folder, in the main storage in Android
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
// the 'temp.pdf' is the name you want for your file.
directoryEntry.getFile('temp.pdf', { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
// great success!
console.log('Write of file completed.');
};
fileWriter.onerror = function (e) {
// Meh - fail
console.log('Write failed');
};
fileWriter.write(blob);
} );
} );
});
};
req.send();}

cordova media plugin isnt working on android 4.4 and 5.0.0

i have tried running cordova media plugin in both kitkat and lollipop but it shows no response.
Not even the 3rd parameter for error's function is running.
I have also read almost every article or question about this problem and tried every way i could but nothing worked.
All i finally concluded was that this plugin is not fully supported in android versions above 4.1
I have tried:
<script>
document.body.onload="ready()";
function ready()
{
document.addEventListener("deviceready",function() {
var src;
// src's value
var med=new Media(src,
function() {
alert("success");
},
function(e)
{
alert("failed code: "+e);
});
med.play();
med.release();},false);
}
</script>
here is what i have tried replacing with //src's value
src = 'cdvfile://audio.mp3';
src = 'file:///android_asset/www/audio.mp3';
src = "cdvfile:///android_asset/www/audio.mp3";
src = "audio.mp3";
even after that stupid conclusion i wrote about up there, i still am doubtful that how it still runs on some devices with same os. So, any ideas of making audio files play in cordova app?
MORE INFO:
1>My project structure
appName
|___www
|___[+]css
|___[+]js
|___index.html
|___[+]img
|___audio.mp3
2>I am targeting 6.3.0 marshmallow 😋
Media definitely works for me on marshmallow - albeit I use wav files rather than mp3. I use
audioFail = loadAudio('sounds/no.wav'); where the file is stored in www/sounds
The media constructor is asynchronous but your code uses med immediately after issuing the call to the constructor - have you confirmed that med exists and is defined before you try to call med.play()?

Streaming mp3 in Xamarin Android MediaManager not working

I'm using this nu-get package to stream mp3 url in a Xamarin Android project:
https://github.com/martijn00/XamarinMediaManager
I followed the instructions in the link up there... and it shows the music playing in the notification bar but it is not working (no sound and it's not even starting the song).
Code snippet:
clickButton.Click += (sender, args) =>
{
ClickButtonEvent();
};
private static async void ClickButtonEvent()
{
await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");
}
I built the sample included in the link, and I got the same result from their sample. Also deployed on real device too, same result!
Image:
Am I missing something ?
Or is the library broken ?
I ran into this using Android Emulator on Hyper-v. It turns out that the network is set to internal. So the http://www.montemagno.com/sample.mp3 could not be found. My workaround:
Hyper-v -> Virtual Switch Manager, add an external network.
Hyper-v -> Virtual Machines->Settings, add new hardware->Network adapter and set to external network.
"Visual Studio Emulator for Android" desktop app, launch phone vm,
in Visual Studio, deploy and run app.
Sound should work from external source now.
Permissions maybe? In the project site it states that for Android:
You must request AccessWifiState, Internet, MediaContentControl and
WakeLock permissions
By default example use ExoPlayerAudioService.
There are issue with url escape in ExoPlayerAudioService.GetSource method
private IMediaSource GetSource(string url)
{
string escapedUrl = Uri.EscapeDataString(url);
var uri = Android.Net.Uri.Parse(escapedUrl);
var factory = URLUtil.IsHttpUrl(escapedUrl) || URLUtil.IsHttpsUrl(escapedUrl) ? GetHttpFactory() : new FileDataSourceFactory();
var extractorFactory = new DefaultExtractorsFactory();
return new ExtractorMediaSource(uri
, factory
, extractorFactory, null, this);
}
string escapedUrl = Uri.EscapeDataString(url);
I.E. http://example.com/path_to_audio.mp3 will be escaped to "http%3A%2F%2Fexample.com%2Fpath_to_audio.mp3" as result HTTP error.
To fix just skip url escape.

Phonegap - Local storage not working - Android

I'm using Local Storage to pass values between pages in order to create a scroll to effect (user clicks link and is scrolled to particular part of the page based on ID)
I was previously using cookies but that didn't seem to work on Android, I read that local storage was supported so switched over to that. It works completely fine when in the browser but as soon as its packaged as a native app I lose all functionality? The API states that it should be supported, any ideas?
Here's my code:
Base URL:
var storage = window.localStorage;
$("a.scroll_link").click(function(event) {
event.preventDefault();
var value = $(this).attr("id");
storage.setItem("key",value);
console.log(value);
window.location=$(this).attr("href");
});
Receiving URL:
$(function () {
var value = window.localStorage.getItem("key");
if (value != "" && value != "undefined" && value != null) {
var storage = window.localStorage;
storage.setItem("key",value);
var scroll_type = "";
if ($.browser.webkit) {
scroll_type = "body";
} else {
scroll_type = "html";
}
$(scroll_type)
.stop()
.animate({
//get top-position of target-element and set it as scroll target
scrollTop: ($("#" + value).offset().top - 25)
//scrolldelay: 1.5 seconds
}, {
duration: 1500,
complete: function () {
storage.removeItem("key");
},
});
}
});
The code works fine in the browser just not natively, any ideas?
Thanks,
Use document.addEventListener("deviceready", onDeviceReady, false) instead of $(function(){...}
http://docs.phonegap.com/en/2.5.0/cordova_events_events.md.html#deviceready
1.Glad to know you solve your first problem. As gmh04 say, I think you should replace your init event with 'deviceready' which is triggered when the app start running.
2.
You mean window.localStorage.getItem("key") return null in Receiving URL?
I do not exactly encounter a problem as what you describe. However, you may try to move your code in receiving url to the same page of base url. I have tried for times and be very sure that the localStorage will work in the same page.
I would like add that there's a bug on the 2.6.0 version of cordova.js that make localStorage don't work on Android:
https://issues.apache.org/jira/browse/CB-3063
On the 2.5.0 version it works perfectly, and it is already fix on the 2.7.0 rc.

FIle API - Phonegap?

Can anybody explain how to list a folder of files on a page using the Phonegap File API for Android?
I would like to list all .mp3 files if possible, but have read through all the phonegap docs (http://docs.phonegap.com/en/1.0.0/phonegap_file_file.md.html) and cant figure it out at all!
it is a bit of a pain in the #$$ but doable. Start with this code:
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("Music", {create: false, exclusive: false}, getDirSuccess, fail);
}
function getDirSuccess(dirEntry) {
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
function readerSuccess(entries) {
var i;
for (i=0; i<entries.length; i++) {
// Assuming everything in the Music directory is an mp3, go nuts
// otherwise check entries[i].name to see if it ends with .mp3
}
}
I'm writing all this example code outside of an IDE so there may be bugs but that should get you going.
Paul, did you add a fail() function? That will be required in Simon's example code. The api docs example has:
function fail(evt) {
console.log(evt.target.error.code);
}
You could also save one step in Simon's code if you just wanted a proof of concept, since fileSystem.root is already a dirEntry (and it saves you the potentially buggy step of having to use a directory name such as "Music" which might or might not be there):
function onFileSystemSuccess(fileSystem) {
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
function readerSuccess(entries) {
var i;.......
which works for me.
However, what I get are the contents of the root directory of the app, apparently, my app being called be.qan.blaActivity, so, if I ask it for fileSystem.root.name it tells me "be.qan" and the fileSystem.root.path is undefined. Thus, my question here would be: how can I break out of this sandbox, if that is indeed what I am sitting in, and can I access the sd_card directories or other parts of the file system (since iOS still does not even have external storage)?
What I am getting by way of file names in readerSuccess are names such as "databases", "app_database", "cache" and "lib" which do not even show up when I do a search with Astro FileManager, so I strongly suppose they are part of a virtual file system that Cordova is creating for the app or so. Probably there is still a lot I am missing and folks more knowledgeable than I can set me straight, but that's what I am guessing so far.
Hi I use this code and it works for me .. can try it
$('#recordingList').on('pagecreate', function(event) {
generateRecordingList();
});
function generateRecordingList(){
//request for the file system
window.resolveLocalFileSystemURI("file:///sdcard/rem", onFileSystemSuccess, onError);
}
function onFileSystemSuccess(fileSystem){
alert("FileSystem success : " + fileSystem.name);
}
function onError(error){
alert(error.target.error.code);
}

Categories

Resources