PhoneGap and Xcode: Play and Stop a sound with the same button - ios

I've searched all the whole Internet to find a solution to my problem, but I didn't find it :(
So, I'm doing a SoundBoard app using Phonegap and Xcode and my problem is about stopping the sound from the same button I used to play the audio, but I can't do it, I think it's impossible for me!
This is a part of the Javascript with the Play and Stop functions and IsPlaying function, that I created trying to determine if the sound is playing or not using the variable SoundPlaying:
<script type="text/javascript" charset="utf-8">
SoundPlaying = false
...
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);});
// Play audio
my_media.play();
}
// Stop audio
//
function stopAudio() {
if (my_media) {
my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
function IsPlaying(url) {
if (SoundPlaying==false) { playAudio(url); SoundPlaying=true; alert('SoundPlaying is ' + SoundPlaying); }
else { stopAudio(); SoundPlaying=false; alert('SoundPlaying is ' + SoundPlaying); }
}
</script>
And then I tried to call the IsPlaying function from a button: if the variable SoundPlaying is false then play the sound and set SoundPlaying as true, ELSE stop the sound and set SoundPlaying as false
<button id='button'
style="background-image:url(imgs/image.png);"
onClick = "IsPlaying('msk/sound.mp3');" >
</button>
It's like the ELSE part of the statement isn't checked, but the IF part yes. Indeed i can see the alert window saying that SoundPlaying is true but not if I click on the button a second time....or a third...and so on.
Can you please help me??
Thank you very much!
Vittorio

I think you are going to deep into the code ...
What do you think about this solution?
// Audio player
//
var soundfile = null;
// Play audio
//
function playPauseAudio(src) {
if (soundfile == null) {
// Create Media object from src
soundfile = new Media(src, onSuccessAudio, onErrorAudio);
soundfile.play();
} else {
soundfile.stop();
soundfile = null;
}
}
// Callback
function onSuccessAudio(){};
function onErrorAudio(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}

i used this one in my phonegap project, works great. I even with a pause button:
<script type="text/javascript">
function hide(elementID)
{
document.getElementById(elementID).style.display = 'none';
}
function show(elementID)
{
document.getElementById(elementID).style.display = '';
}
</script>
<img id="off" src="images/general/sound-off.png" width="40" height="32" onClick="show('on'); hide('off'); playAudio();" alt="on">
<img id="on" src="images/general/sound-on.png" width="40" height="32" onClick="show('pause'); hide('on'); pauseAudio();" style="display:none;" alt="off">
<img id="pause" src="images/general/sound-pause.png" width="40" height="32" onClick="show('on'); hide('pause'); playAudio();" style="display:none;" alt="on">
For the audio, i use the playaudio(), pauseaudio() and stopaudio() command in the onclick.
Hope this helps :-)

Related

How to play an audio file through Ionic on iOS?

I am using cordovo media plugin to play an audio file on button click. It is working fine on Android but I don't understand the problem with iOS. Here is the code inside a controller:
var url = '';
if(ionic.Platform.isAndroid() == true){
url = "/android_asset/www/sound.wav";
}else{
url = "sound.wav";
}
$scope.playAudio = function() {
// 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: " + JSON.stringify(err));
}
);
console.log("Play");
// Play audio
my_media.play();
}
I have spent many of my hours to figure out the problem, but I have no idea what has gone wrong. I will be genuinely thankful to you if you can help me out.
Thanks in advance.

YouTube IFrame API stopping before end

Is it possible to stop a video using the YouTube API one second before the end or just stopping it resetting back to the beginning? This is regardless of the length of the video itself.
Thanks in advance
I disagree with the argument of NOT being able to stop a video before it ends. Specifically, in the API, you have access to:
https://developers.google.com/youtube/js_api_reference#Playback_status
Player.getCurrentTime();
Player.getDuration();
If you were to monitor the player object and compare these two, you could easily stop the video before it ends. An example would be (although probably not good in production):
setInterval(function() {
var player = getPlayer(); //retrieve the player object
if(player) {
var duration = player.getDuration();
var current = player.getCurrentTime();
if((duration - current) <= 1) {
player.stopVideo();
}
}
}, 1000); //every second
I ran into an issue where for some reason the iframe player was stopping the video before the video's end, and so not triggering the ENDED event, and ran into this question while trying to find a solution for that. Since my approach can solve your problem as stated, here's what I did (I left the console.log() debug lines in to make it easier for someone else using this to play around with):
var player_timeout;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
console.log("PLAY [" + event.data + "]");
timeout_set();
}
if (event.data == YT.PlayerState.PAUSED) {
console.log("PAUSED [" + event.data + "]");
clearTimeout(player_timeout);
}
}
function timeout_func() {
console.log("timeout_func");
player.stopVideo(); // or whatever other thing you want to do 1 second before the end of the video
}
function timeout_set() {
console.log("timeout_set");
var almostEnd_ms = (player.getDuration() - player.getCurrentTime() - 1) * 1000;
console.log("almostEnd_ms: " + almostEnd_ms);
console.log("player.getCurrentTime(): " + player.getCurrentTime());
player_timeout = setTimeout(timeout_func, almostEnd_ms);
}

Play local audio files in ios cordova

I am using media plugin to play local audio files (inside /www folder). This perfectly works in android but in iOS the error "Cannot play the audio file from resource…." is coming.
Please check the below screenshot and coding. How should i solve this to play local audio files.
<script type="text/javascript">
function getPhoneGapPath() {
'use strict';
var path = window.location.pathname;
var phoneGapPath = path.substring(0, path.lastIndexOf('/') + 1);
return phoneGapPath;
};
// Audio player
var my_media = null;
var mediaTimer = null;
// Play audio
function playAudio() {
if (my_media == null) {
// Create Media object from src
my_media = new Media(getPhoneGapPath() +'button-click.wav', onSuccess, onError);
} // else play current audio
// Play audio
my_media.play();
}
// Pause audio
//
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');
}
</script>

Media is not playing in iOS phonegap 1.5 app

I am developing iOS app using phonegap 1.5. In this app I am using phonegap's Media API to play mp3 files. But it's not working on iOS. Same codebase works on Android without any issue.
Code:
Audio.js
//
var my_media = null;
var mediaTimer = null;
function playAudio(src) {
//alert("inside");
//if (my_media == null) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
//alert(my_media);
//} // else play current audio
// Play audio
my_media.play();
//alert("Played");
}
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
I am including Audio.js in my html file and then calling function
playAudio("audio/welcome.mp3");
All of my mp3 files reside in www/audio folder.
I debugged using alert statements, call comes till this line of code
my_media = new Media(src, onSuccess, onError);
No error callback or no errors in console of xcode.
Am I missing something here? What could be the issue?
Phonegap is pretty difficult with having stuff behaving differently that it should, especially when it comes to media and plugins. You need to have something that changes the file path based off of the device (using the Cordova Device Plugin):
//Gets Device Platform
document.addEventListener("deviceready", getDevicePlatform, false);
function getDevicePlatform() {
$scope.devicePlatform = device.platform;
console.log(device.platform);
}
Then to set the media player file path correctly:
if ($scope.devicePlatform == "Android") {
var songFilePath = '/android_asset/www/res/' + song.name + '.mp3';
}
else {
var songFilePath = 'res/' + song.name + '.mp3';
}
$scope.song = new Media(songFilePath);
The song .name is something special I had to dynamically get the path, but the main thing is that for Android devices you need the /android_asset/, but for other devices like iOS and PhoneGap you can use normal file paths to media inside the /www folder.

Play captured audio in phonegap

I am able to capture audio and I have the full path to the captured file, but I am having trouble getting it to play the most recent captured file.
I am using Phongap 2.5 and also Jquery Mobile on iOS 6.1.
Code:
<script type="text/javascript" charset="utf-8">
function captureSuccess(mediaFiles) {
var i, len;
var formatSuccess = function (mediaFile) {
document.getElementById('capture-data').innerHTML =
"Duration: <strong>" + mediaFile.duration + "</strong><br/>";
};
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
// uploadFile(mediaFiles[i]);
document.getElementById('capture-result').innerHTML = "<strong>" + (i+1) + " file(s), Path: " + mediaFiles[i].fullPath + "</strong><br/>";
mediaFiles[i].getFormatData(formatSuccess, formatError);
readDataUrl = mediaFiles[i].fullPath;
};
console.log("captureImageSuccess");
}
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
function captureAudio() {
// Launch device audio recording application,
// allowing user to capture up to 2 audio clips
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit: 2});
}
$("#audio-result").click(function() {
function playAudio(mediaFiles) {
var play = document.getElementById('audio-result').src =
mediaFiles[i].fullPath;
}
});
</script>
</head>
<body>
<button onclick="captureAudio();">Capture Audio</button> <br>
<div class="result-block">
Capture Result: <span id="capture-result"></span><br/>
<span id="capture-data"></span><br/>
<button id="audio-result">Play audio</button>
</div>
</body>
</html>
you can play your media as below
var my_media = null;
// here src is the uri of your media
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play()
// Pause audio
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
// Stop audio
function stopAudio() {
if (my_media) {
my_media.stop();
}
}

Resources