I have created an Android app from html5 and JavaScript using ionic/Cordova framework. In there I create and play an audio object as:
var myAudio = new Audio("myfile.mp3") ;
myAudio.play();
If I install the generated apk on Android API 21, audio plays fine. If I install it on API 19 it doesn't play.
Any help on this is really appreciated.
Hi did you install the cordova media plugin?
I did something like that in the past with cordova 4.0.0 (definitely worked on android 19 (4.4.2 to be accurate)):
AckSound:function(){
try{
var pathMedia;
if(device.platform ==='iOS'){
pathMedia ='';
} else {
pathMedia = app.getCordovaPath();
}
var snd =new Media(pathMedia+'mySound.mp3');
// Update media position every second
var mediaTimer = null;
mediaDuration = snd.getDuration();
console.log("mediaDuration is " + mediaDuration);
snd.play();
if(mediaTimer==null){
mediaTimer = setInterval(function () {
// get media position
snd.getCurrentPosition(
// success callback
function (position) {
if (position > 0) {
console.log((position) + " sec");
} else {
//if position isn t > 0, the file is over
snd.stop();
clearInterval(mediaTimer);
mediaTimer = null;
snd.release();
delete snd;
}
},
// error callback
function (e) {
console.log("Error getting pos=" + e);
}
);
}, 100);
};
delete snd;
} catch(err){
console.log("Error: in AudioManagement.AckSound(), Error is " + err);
}
console.log("AudioManagement.AckSound() stops");
}
},
Here is a full example: https://github.com/nyluje/TestMediaPluginCordova
Related
Trying to play audio files from the external storage of phone.
Went through this plugin first finding the URI for a particular mp3 file. Then passed that to the cordova-plugin-media instance.
// find music file URI from the sdcard
new ExternalStorageSdcardAccess( fileHandler ).scanPath( "file:///storage/C67A-18F7/Music/" );
function fileHandler( fileEntry ) {
// console.log( fileEntry.name + " | " + fileEntry.toURL() );
}
// create a button instance
let mbutton = new Button({
centerX: 0, top: [fbutton,100],
text: 'play music'
}).appendTo(ui.contentView);
// call the play media function from the button
mbutton.on('select', () => {
// load and play the music:
playAudio("file:///storage/C67A-18F7/Music/demo/testSound.mp3")
});
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function () {
console.log("playAudio():Audio Success");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err.code + err.message);
},
// status callback
function (status) {
console.log("playAudio():Audio Status: " + status);
}
);
// Play audio
my_media.play();
my_media.setVolume('1.0');
}
I checked the adb for log. This is what I got specifically hitting those buttons - http://paste.ubuntu.com/25767292/
incoming-operation: 'Call' on 'cordova.plugin' (o13) with method 'exec' with properties {action=create, arguments=["d39113d0-b5f5-bf2d-8a84-5afbbc6ae9a0","file:///storage/C67A-18F7/Music/demo/testSound.mp3"], callbackId=Media975330222}
incoming-operation: 'Call' on 'cordova.plugin' (o13) with method 'exec' with properties {action=startPlayingAudio, arguments=["d39113d0-b5f5-bf2d-8a84-5afbbc6ae9a0","file:///storage/C67A-18F7/Music/demo/testSound.mp3",null], callbackId=INVALID}
outgoing-operation: 'Notify' o13 of 'finish' with arguments {message=S01 Media975330222 s, status=1, keepCallback=false, callbackId=Media975330222}
ExtMediaPlayer-JNI: env->IsInstanceOf fails
MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
ExtMediaPlayer-JNI: env->IsInstanceOf fails
MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
I am using Capacitor with an ionic react project and was able to get cordova-plugin-media playing local files by using it in conjunction with cordova-plugin-file. I am the ionic-native wrappers, but I think its the same code here.
NOTE: iOS requires you to remove 'file://' and Android does not.
const finishedFilePath = `${File.applicationDirectory}public/assets/audio/file.mp3`;
const hybridTransitionAudioFile = Media.create(isPlatform('ios') ? transitionFilePath.replace('file://', '') : transitionFilePath);
hybridTransitionAudioFile.play();
1- install this
https://play.google.com/store/apps/details?id=com.adobe.phonegap.app&hl=en
2- install this
http://docs.phonegap.com/getting-started/1-install-phonegap/desktop/
3- connect your laptop and your phone on same network
4- follow the getting started on this and run it on your phone , i suppose you wont get the same error , because im my case it dose not work in browser nor emulator in case of phone gap
Reference:
https://phonegap.com/getstarted/
give feed back so i can update my answer here
HTML PART
for audio src
<audio id="successSound" src="/android_asset/www/audio/correct.mp3" type="audio/mpeg"></audio>
<audio id="errorSound" src="/android_asset/www/audio/error.mp3" type="audio/mpeg" ></audio>
</body>
</html>
Example of my version that works i hope there is help in it
playAudio("errorSound");
var my_media = null;
var mediaTimer = null;
function playAudio(id) {
var audioElement = document.getElementById(id);
var src = audioElement.getAttribute('src');
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play();
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition((position) + " sec");
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
// onSuccess Callback
//
function onSuccess() {
}
// onError Callback
function onError(error) {
switch(error.code){
case MediaError.MEDIA_ERR_ABORTED:
alert('MEDIA_ERR_ABORTED code: ' + error.code);
break;
case MediaError.MEDIA_ERR_NETWORK:
alert('MEDIA_ERR_NETWORK code: ' + error.code);
break;
case MediaError.MEDIA_ERR_DECODE:
alert('MEDIA_ERR_DECODE code: ' + error.code);
break;
case MediaError.MEDIA_ERR_NONE_SUPPORTED:
alert('MEDIA_ERR_NONE_SUPPORTED code: ' + error.code);
break;
}
}
EDIT : I just created a new Meteor Project and it worked :D wow.But it still doesnt work on my core project..looks like i have different settings.
In my Meteor.js project i have 4 .mp3-files located in public/sounds/xyz.mp3.
I load these .mp3 with :
let soundRequest = new XMLHttpRequest();
soundRequest.open('GET', this._soundPath, true);
soundRequest.responseType = 'arraybuffer';
let $this = this;
soundRequest.onload = function () {
Core.getAudioContext().decodeAudioData(soundRequest.response, function (buffer) {
$this.source.buffer = buffer;
$this.source.loop = true;
$this.source.connect($this.panner);
});
};
soundRequest.send();
This WORKS on google Chrome, but when i build the app via meteor run android-device, i get the following error message : DOMException: Unable to decode audio data
I wonder if this is a bug because loading .png or .jpg works just fine in the mobile version. I have not installed any packages beside meteor add crosswalk but deinstalling this doesnt help either.
You shouldn't need to do a http request to get a local resource. You can just refer to a local url. On the Android device the path is different. See this code:
function getSound(file) {
var sound = "/sounds/"+file;
if (Meteor.isCordova) {
var s;
if (device.platform.toLowerCase() === "android") {
sfile = cordova.file.applicationDirectory.replace('file://', '') + 'www/application/app' + sound;
}
else {
sfile = cordova.file.applicationDirectory.replace('file://', '') + sound;
}
var s = new Media(
sfile,
function (success) {
console.log("Got sound "+file+" ok ("+sfile+")");
s.play();
},
function (err) {
console.log("Get sound "+file+" ("+sfile+") failed: "+err);
}
);
} else {
var a = new Audio(sound);
a.play();
}
}
On a device it loads the sound file asynchronously and then plays it. In the browser it just loads and plays it synchronously.
This web API is not supported on android device but works on chrome browser of android
Check browser specification in this link
https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/decodeAudioData
I've been trying to implement the Phonegap Media plugin to playback an audio file.
I understand I'll need to refer to the correct file path (android_asset/www/...) and use an .amr file as per the docs but it's still returning with a code: 1 error, which I believe has something to do with a disruption in getting the file.
function sound(){
var backgroundMusic = null;
var musicPlaying = false;
function playAudio(){
function getPhoneGapPath() {
var devicePlatform = device.platform;
if (devicePlatform === "iOS") {
path = "";
} else if (devicePlatform === "Android" || devicePlatform === 'android') {
path = "/android_asset/www/";
}
return path;
};
var backgroundMusic = new Media(getPhoneGapPath() + 'audio/bg.amr', success, error);
function success(){
backgroundMusic.release();
alert('success');
}
function error(e){
alert(getPhoneGapPath() + 'audio/bg.amr');
alert(JSON.stringify(e));
}
if (!musicPlaying) {
backgroundMusic.play();
musicPlaying = true;
$(".audio-off").css('display', 'block');
$(".audio-on").css('display', 'none');
}
else if (musicPlaying){
backgroundMusic.stop();
musicPlaying = false;
$(".audio-on").css('display', 'block');
$(".audio-off").css('display', 'none');
};
}
$(".audio-on, .audio-off").on("touchstart", function() {
playAudio();
});
}
window.onload = function() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
sound();
//other code...
}
After reading so many questions and tutorials I can't see where I've gone wrong. The media plugin is also definitely included in my config.xml as well.
I'm testing on my Nexus 5 with Lollipop 5.0.1.
Any help would be greatly appreciated, thanks :-)
I'm trying to create an app that allows the user to record audio. I'm using the cordova-plugin-media for this.
Using the sample from the documentation I can record sound on iOS (specifying a *.wav file), Android (*.amr), Windows Phone 8 (*.aac), but Windows Phone 8.1 doesn't work. I've tried it with *.mp3, *.wma, and *.m4a, but in every case I get this error:
No suitable transform was found to encode or decode the content.
Here's part of the code:
var that = this;
try {
this._media = new Media('recording.mp3', function () {
that._log('Audio success');
}, function (e) {
that._log('Error: ' + e.code + ': ' + e.message);
});
// Bind buttons
document.querySelector('#recordStart').addEventListener('click', function () {
// Record
that._log('Recording...');
that._media.startRecord();
});
document.querySelector('#recordStop').addEventListener('click', function () {
that._log('Recording stopped');
that._media.stopRecord();
});
}
catch (e) {
this._log('An error occurred!');
this._log(e.message);
}
I manage to play several sounds on Android (Cordova 4.1) but now I would like to dynamically change the volume of each video.
My code for playing sounds is the following:
function onDeviceReady() {
document.querySelector("#play").addEventListener("touchend", playMP3(), false);
function playMP3() {
var mp3_1 = getMediaURL("audio/sound1.mp3");
var mp3_2 = getMediaURL("audio/sound2.mp3");
media1 = new Media(mp3_1, null, mediaError);
media2 = new Media(mp3_2, null, mediaError);
media1.play();
media2.play();
}
function getMediaURL(s) {
if(device.platform.toLowerCase() === "android") return "/android_asset/www/" + s;
return s;
}
function mediaError(e) {
alert('Media Error');
alert(JSON.stringify(e));
}
}
Then I would like to control volume with something like media1.volume = 0.5; from outside the onDeviceReady function but I can't make it work...
Any idea of what I'm missing?
Finally, the whole package to play and control sounds with Cordova 4.1 and Android 4.4 wich worked for me. To set the volume call the function with something like onclick=setVolume(media1, "0.5")
Hope it can help !
var media1 = null;
var media2 = null;
//set volume of one sound
function setVolume(media, volume) {
if (media) {
media.setVolume(volume);
}
}
//play the 2 sounds at the same time
function playMP3() {
var mp3_1 = getMediaURL("audio/media1.mp3");
var mp3_2 = getMediaURL("audio/media2.mp3");
media1 = new Media(mp3gauche, null, mediaError);
media2 = new Media(mp3droite, null, mediaError);
media1.play();
media2.play();
}
//for android devices (need the Device Cordova plugin)
function getMediaURL(s) {
if(device.platform.toLowerCase() === "android") return "/android_asset/www/" + s;
return s;
}
//help to get log when errors occur
function mediaError(e) {
alert('Media Error');
alert(JSON.stringify(e));
}
//launch the 2 sounds when the device is ready
function onDeviceReady() {
document.querySelector("#playMp3").addEventListener("touchend", playMP3(), false);
}