I'm using Cordova media plugin for playing audio sound in my mobile application
I tried many codes but I didn't figure out what I'm doing wrong at the bottom I put two piece of code that I tried them
the first code (js code in a separate file)
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
var myMedia = new Media("../sounds/clapping.mp3");
myMedia.play();
}
};
app.initialize();
the second code (js code in a script tag) :
document.addEventListener("deviceready", function(){
var myMedia = null;
function playAudio() {
var src = "sounds/clapping.mp3";
if(myMedia === null) {
myMedia = new Media(src, onSuccess, onError);
function onSuccess() {
console.log("playAudio Success");
}
function onError(error) {
console.log("playAudio Error: " + error.code);
}
}
myMedia.play();
}
document.getElementById("playAudio").addEventListener("click", playAudio);
});
with a button :
<button id ="playAudio">PLAY</button>
How can I solve this problem ?
Wasted 2 hours on this, sharing it here:
This should not be this difficult. No full example at: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/
Simple step by step details:
Put my file in www:
Example at: www/audio/button-1.mp3
Install plugin:
cordova plugin add cordova-plugin-media
Copy paste code below:
`
function getFullMediaURL(s) {
return cordova.file.applicationDirectory + 'www/audio/button-1.mp3'
}
function playMP3() {
let src = getFullMediaURL();
var myMedia =
new Media(src,
function () { },
function (e) { alert('Media Error: ' + JSON.stringify(e)); }
);
myMedia.play();
myMedia.setVolume('1.0');
}
`
Step 4: Call below where you need play sound:
playMP3();
To answer your question, you can find the working sample of cordova app using Media Plugin in the following github page.
As mentioned in the sample project's README, you gotta install cordova device plugin as well to check the device platform.
Also to clarify the doubt you mentioned in the comment, android_asset refers to the project's root folder.
Related
I'm trying to register a video in my application through the cordova plugin Media Capture. According to the documentation, this is my code :
startRegistration(){
var captureSuccess = function(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
// do something interesting with the file
}
};
// capture error callback
var captureError = function(error) {
};
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:1});
}
I tried compiling the code but I received the following error :
Property 'device' does not exist on type 'Navigator'
What is going wrong?
Its used to work like this in Ionic 1 but not anymore. Now you will need to install #ionic-native/media-capture as well.
Skip first command if you already have latest plugin installed.
ionic cordova plugin add cordova-plugin-media-capture
npm install #ionic-native/media-capture
After installing you can use this plugin like this
import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '#ionic-native/media-capture/ngx';
constructor(private mediaCapture: MediaCapture) { }
...
let options: CaptureImageOptions = { limit: 3 }
this.mediaCapture.captureImage(options)
.then(
(data: MediaFile[]) => console.log(data),
(err: CaptureError) => console.error(err)
);
Here is the link where you can find details
Corodva or Capacitor Please follow accordingly. You can find guides for both in this link.
I'm trying to write file to local storage on Android device, using ngCordova function found on ionic forum. This is how the function looks:
$scope.exportClicked = function(options) {
var deferred = $q.defer();
$window.resolveLocalFileSystemURL($window.cordova.file.dataDirectory,
function(dir) {
dir.getFile('text.txt', {
create: true
}, function(fileEntry) {
fileEntry.createWriter(
function(fileWriter) {
if (options['append'] === true) {
fileWriter.seek(fileWriter.length);
}
fileWriter.onwriteend = function(evt) {
evt.fileEntry = fileEntry;
deferred.resolve(evt);
};
fileWriter.write(data);
},
function(error) {
deferred.reject(error);
}
);
}, function(er) {
deferred.reject(error);
});
});
return deferred.promise;
};
When I'm running app through ionic in webbrowser, it gives me an error:
TypeError: Cannot read property 'file' of undefined
at Scope.$scope.exportClicked (app.js:27)
I've installed cordova file plugin, but it looks like it can't find cordova.file functionality.
On Android device it won't work either. Any ideas?
You forgot to install file cordova plugin. https://github.com/apache/cordova-plugin-file
$window.cordova isn't defined. Since you are using ngCordova, and ngCordova has official support for the file plugin, I would start with the ngCordova documentation for the file plugin. Here is the bit you might be interested in:
$cordovaFile.writeFile(cordova.file.dataDirectory, "file.txt", "text", true)
.then(function (success) {
// success
}, function (error) {
// error
});
You also get the added bonus have having more readable code when you use the ngCordova implementation.
If you would rather follow your original example more closely, try replacing $window.cordova with window.cordova, or simply cordova.
I'm try to create a config file to keep some configurations of my app. I'm using SAPUI5 and cordova file.
The intention is create a conf.txt to keep the URL, PORT and LDAP data to access my system. However, these information can change, so I need to update the file.
In my app, I've made the function deviceready when the application starts, and created the conf.txt:
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
/*jQuery.sap.require("model.Config");
var conf = new Configuration();
conf.init();*/
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("conf.txt", {create : true,exclusive : false},gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
//alert(fileEntry.fullPath);
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
alert("OK");
};
var conf = "URL=\r\nPORT=80\r\nLDAP=false";
writer.seek(writer.length);
writer.write(conf);
}
function fail(error) {
alert(error.code);
}
I didn't do nothing different of other examples. But, as I've commented in onDeviceReady function, I tried to create a class to use to create the file, read and update it.
All examples that I found reference the deviceready event. Can I just use the methods of FileWriter and FileReader on this event?
It's my Configuration Class:
function Configuration() {
this.fileName = "conf.txt";
this.init = function() {**How to use the cordova API here**};
this.read = function(){**How to use the cordova API here**};
this.update= function(){**How to use the cordova API here**};
}
Thanks for help!
As suggested by Njtman, I got to save the informations in file without cordova file plugin just using localstorage.
I'd like to share the solution found.
index.html on deviceready event:
jQuery.sap.require("model.Config");
var conf = new Configuration();
sap.ui.getCore().setModel(conf, "Config");
conf.init();
Configuration class:
sap.ui.model.json.JSONModel.extend("Configuration", {
url: "",
port: "80",
defaultport: true,
ldap: false,
init : function() {
var deferred = $.Deferred();
console.log("INITIALIZING...");
var config = JSON.parse(window.localStorage.getItem("config"));
if(config == null){
console.log("CONFIG IS NULL");
window.localStorage.setItem("config", JSON.stringify(
{"URL": this.url, "PORT": this.port, "DEFAULTPORT": this.defaultport, "LDAP": this.ldap}
));
}
deferred.resolve();
this.setData(JSON.parse(window.localStorage.getItem("config")));
this.setVars();
console.log(this.getJSON());
return deferred.promise();
},
save: function(url, port, defaultport, ldap){
var deferred = $.Deferred();
console.log("SAVING...");
window.localStorage.setItem("config", JSON.stringify(
{"URL": url, "PORT": port, "DEFAULTPORT": defaultport, "LDAP": ldap}
));
deferred.resolve();
this.setData(JSON.parse(window.localStorage.getItem("config")));
this.setVars();
return deferred.promise();
},
setVars: function(){
this.url = this.getProperty("/URL");
this.port = this.getProperty("/PORT");
this.defaultport = this.getProperty("/DEFAULTPORT");
this.ldap = this.getProperty("/LDAP");
}
});
Now I can read and update my json file.
I'm following this tutorial for having banner ads in my android application.
https://blog.nraboy.com/2014/06/using-admob-ionicframework/
The problem is that I get an error callback from the plugin which is only telling me :
Invalid action
I ran the cordova plugin add for the plugin, I modified the admob publisher id, I used the sample code from the tutorial right above but it always get stuck in the second callback function which is the error case callback.
Here is the code I used :
var admobApp = angular.module('myapp', ['ionic'])
.run(function($ionicPlatform, $ionicPopup) {
$ionicPlatform.ready(function() {
if(window.plugins && window.plugins.AdMob) {
var admob_key = device.platform == "Android" ? "ANDROID_PUBLISHER_KEY" : "IOS_PUBLISHER_KEY";
var admob = window.plugins.AdMob;
admob.createBannerView(
{
'publisherId': admob_key,
'adSize': admob.AD_SIZE.BANNER,
'bannerAtTop': false
},
function() {
admob.requestAd(
{ 'isTesting': false },
function() {
admob.showAd(true);
},
function() { console.log('failed to request ad'); }
);
},
function() { console.log('failed to create banner view'); }
);
}
});
});
I'm new to Ionic and Cordova, so I'm sure I'm missing something basic, but my problem is a packaged APK does not play sounds on an Android device. I can get the sound to play in the Ripple emulator just fine with the following code:
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.playStartBell = function () {
var media = new Media('media/startBell.mp3', function () {
console.log('good');
}, function (err) {
console.log('bad: ', err);
});
media.play();
},
$scope.playStopBell = function () {
var media = new Media('media/stopBell.mp3', function () {
console.log('good');
}, function (err) {
console.log('bad: ', err);
});
media.play();
}
}])
I've used Cordova to install the media plugin: $cordova plugin add org.apache.cordova.media
According to this SO post, a value needs to be added to the config.xml, but I'm not sure how to do it properly for Ionic/Cordova.
Turns out that you have specify path starting with the /android_asset/www prefix like so:
/android_asset/www/
So changing my code to the following worked. Note you'll want to detect what device you're running on to determine the appropriate location.
.controller('MainCtrl', ['$scope', function ($scope) {
///android_asset/www/
$scope.playStartBell = function () {
var media = new Media('/android_asset/www/media/startBell.mp3', function () {
console.log('good');
}, function (err) {
console.log('bad: ', err);
});
media.play();
},
$scope.playStopBell = function () {
var media = new Media('/android_asset/www/media/stopBell.mp3', function () {
console.log('good');
}, function (err) {
console.log('bad: ', err);
});
media.play();
}
}])