cordova-plugin-media not playing from local URI - javascript

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;
}
}

Related

JavaScript Audio object not working in Android API 19

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

Phonegap media plugin one sound at time

I tried to make an image/sound gallery with PhoneGap media plugin, but I ran into one problem. When I click on a picture, the sound plays, but when I click on another one it plays that one too. Any idea how I can let them play one sound at a time?
<script type="text/javascript" charset="utf-8">
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(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);
}
}
// Pause audio
//
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
// Stop audio
//
function stopAudio() {
if (my_media) {
my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
</script>
<img src="arMonika/audio.png" width="147" height="147" />
<img src="arMonika/k.tech.spec.png" width="141" height="141" />
For those who have the same issue :
When you start defining your player , player or "Media" stores in variable , in your case it is "my_media" .
To solve this problem just define your variable "my_media" as a global var.
and then for each link that should play sound you need to stop your previos media and store new media in that variable like this :
my_media.stop
new Media(src, onSuccess, onError);
just becareful about defining its variable as a GLOBAL variable.
Hoped it helps.

Cannot record audio with Cordova Media plugin on Windows (Phone) 8.1

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);
}

Phonegap play audio with Media plugin

I'm using Media from phonegap to play some audio in my APP.
function playSnd(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);
});
// Play audio
my_media.play();
}
And after I call playSnd('audio.mp3') in my console I recive
Uncaught ReferenceError: Media is not defined index.js:54
LE: I have https://github.com/apache/cordova-plugin-media installed.
You have to wait for ondeviceready event.
document.addEventListener('deviceready', function () {/* your code goes here */});

Click on image to play sound PHONEGAP

I am clicking on my image to call the playAudio(). I am using phonegap to do this.
Here is my function
<script type="text/javascript" charset="utf-8">
// Audio player
//
var my_media = null;
// Play audio
//
function playAudio(src) {
if (my_media == null) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
} // else play current audio
// Play audio
my_media.play();
}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
Here is my image
<input type="image" id="myimage" src="numb/equal.png" style="height:100px;width:100px;margin-top:0px" onclick="playAudio('/android_asset/www/Mobile/sound/'+ abc +'.mp3');"/>
On clicking this image it should play the corresponding mp3. But in my console I am getting "Media is not Defined"
Here is the screenshot of the error
How can i fix this ?
If you are using Phoengap/Cordova, you shouldn't include /android_asset/www/ in the path to the mp3. You can think of that /android_asset/www/ folder as the 'context root' - all relative URLs will automatically have this appended to them.
So just change onclick="playAudio('/android_asset/www/Mobile/sound/'+ abc +'.mp3');" to
onclick="playAudio('./Mobile/sound/'+ abc +'.mp3');" and it should find the correct path to your audio.
I wouldnt do it this way. With HTML5 you can play audio files very easily with the AUDIO TAG. Make your javascript create the element that is described and set the autoplay property.

Categories

Resources