Phonegap play audio with Media plugin - javascript

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

Related

cordova-plugin-media return error failed to start recording using avaudiorecorder code 1 on ios

try to record voice using cordova media plugin on ios but always return error failed to start recording using avaudiorecorder ,code 1
var src = "myrecording.m4a";
mediaRec = new Media(src, function () {
alert("Success");
}, function (err) {
alert(JSON.stringify(err));
});
mediaRec.startRecord();
alert("Recording Started");
console.log(mediaRec);

cordova-plugin-media not playing from local URI

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

does facebook embedded video api still support removeListener()?

According to facebook documentation - https://developers.facebook.com/docs/plugins/embedded-video-player/api , we subscribe to player events
var handleDesktopEvents = function (msg) {
if (msg.type === 'video') {
var player = msg.instance;
var playHandler = player.subscribe('startedPlaying', function() {
// Video started playing ...
player.unmute();
console.log('detected video playing');
ga_virtual_pagehit(msg.id);
console.log('sent event to GA');
playHandler.removeListener('startedPlaying');
// playHandler.release();
});
console.log('detected video ready');
player.play();
FB.Event.unsubscribe('xfbml.ready', handleDesktopEvents, handleDesktopEx);
}
};
var handleDesktopEx = function () {
// Handle pause() and exceptions
console.log('detected pause');
};
FB.Event.subscribe('xfbml.ready', handleDesktopEvents, handleDesktopEx);
It seems that removeListener() is not available on the token returned by subscribe(). With a debugger, we see that there is a method release() available on the token. Should that be used? Is it now official?
Am I doing something wrong?
there was and probably still is, unless FB changed something again, a release() method. it does what removeListen() should be doing.

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.

Sendsms plugin not working on Phonegap

I'm trying to send a message using The "Sendsms"plugin for phone gap on Android.
But when I call the function, I get this error:
Uncaught TypeError: Cannot call method 'send' of undefined at file
This is the JS code I'm using :
function onDeviceReady () {
$('#send').bind('click', function () {
alert('Phone: ' + $('#friendName').val() + ' Message: ' + $('#MessageContent').val());
window.plugins.sms.send($('#friendName').val(),
$('#MessageContent').val(),
function () {
alert('Message sent successfully');
},
function (e) {
alert('Message Failed:' + e);
}
);
});
}
document.addEventListener("deviceready", onDeviceReady, false);
I got the java code from here & added the permission:
<uses-permission android:name="android.permission.SEND_SMS"/>
And added the plugin to Plugins.xml.
Do you know what's the problem ?
Depending on what version of PhoneGap you are using you may just have to go into the smsplugin.js and replace the instances of "PhoneGap" with "cordova".

Categories

Resources