Play local audio files in ios cordova - ios

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>

Related

Audio file does not persist in Cordova with LocalFileSystem.PERSISTENT

I have been trying to store Audio file in persistent storage for two days without success.
So far I am able to create an audio file which records audio from Microphone (The app has the permission) using the code attached below.
The audio file is getting generated & stored successfully, I can play it.
But the real problem is when I close the app and come back and try to play the file it shows error.
"{"message": "Cannot use audio file from resource '/myrecording.wav'",
"code":1}"
The file is not persistent across app sessions even though I used LocalFileSystem.PERSISTENT.
I am not sure whether the problem is with my Media/Audio code or File storage code.
Please find the code attached below:
Below function records the audio from the microphone.
function _recordAudio() {
var deferred = $q.defer();
var src = "myrecording.wav";
alert("SRC:" + src);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(src, {
create: true,
exclusive: false
}, function (fileEntry) {
alert("File " + src + " created at " + fileEntry.fullPath);
var mediaRec = new Media(fileEntry.fullPath,
function () {
alert("Success");
}, function (error) {
alert("error:" + JSON.stringify(error));
});
// Record audio
mediaRec.startRecord();
// Stop recording after 10 sec
var recTime = 0;
var recInterval = setInterval(function () {
recTime = recTime + 1;
if (recTime >= 5) {
clearInterval(recInterval);
mediaRec.stopRecord();
deferred.resolve(fileEntry.fullPath);
}
}, 1000);
}, function (error) {
alert("getFile error:" + JSON.stringify(error));
deferred.reject();
}); //of getFile
}, function (error) {
alert("requestFileSystem error:" + JSON.stringify(error));
deferred.reject();
}); //of requestFileSystem
return deferred.promise;
}
Below function plays the audio.
function _play2() {
var src = "myrecording.wav";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(src, null, function (fileEntry) {
alert("File " + src + " created at " + fileEntry.fullPath);
var mediaRec = new Media(fileEntry.fullPath,
function () {
alert("Success play2");
}, function (error) {
//Getting error after closing and opening the app
//Error message = {"message": "Cannot use audio file from resource '/myrecording.wav'","code":1}
alert("error play2:" + JSON.stringify(error));
});
mediaRec.play();
});
});
}
I solved this problem by passing cdvfile: path to the Media plugin in PlayAudio function code and copying the file from Temp storage to persistent storage.
I had to use localURL of the file.
This part solved my problem:
fileEntry.file(function (file) {
_playNow(file.localURL);
}
For full functions refer code snippets below:
recordAudio: function (projectNo, ItemNo) {
try {
var deferred = $q.defer();
var recordingTime = 0;
_audioLoader = $("#audioLoader");
_audioLoader.show();
UtilityService.showPopup('audio');
_isRecording = true;
_recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav";
_mediaRecord = new Media(_recordFileName);
//Record audio
_mediaRecord.startRecord();
var recordingInterval = setInterval(function () {
recordingTime = recordingTime + 1;
$('#audioPosition').text(_secondsToHms(recordingTime));
if (!_isRecording) {
clearInterval(recordingInterval);
_mediaRecord.stopRecord();
_mediaRecord.release();
deferred.resolve();
}
}, 1000);
//document.getElementById('audioPosition').innerHTML = '0 sec';
$('#audioPosition').text('0 sec');
return deferred.promise;
}
catch (ex) {
alert('WMMCPA|recordAudio:- ' + ex.message);
}
},
Get file path from the persistent storage and send it to the play method.
//To play recorded audio for specific project item
playAudio: function (projectNo, ItemNo) {
try {
_recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav";
var newFileUri = cordova.file.dataDirectory + _recordFileName;
window.resolveLocalFileSystemURL(newFileUri, function (fileEntry) {
fileEntry.file(function (file) {
_playNow(file.localURL);
}, function (error) {
alert("WMMCPA|playAudio.file:-" + JSON.stringify(error));
});
}, function (error) {
alert("WMMCPA|playAudio.resolveLocalFileSystemURL:-" + JSON.stringify(error));
});
}
catch (ex) {
alert("WMMCPA|playAudio:-" + ex.message);
}
}
function _playNow(src) {
try {
var mediaTimer = null;
_audioLoader = $("#audioLoader");
_audioLoader.show();
UtilityService.showPopup('audio');
//Create Media object from src
_mediaRecord = new Media(src);
//Play audio
_mediaRecord.play();
} catch (ex) {
alert('WMMCPA|_playNow.mediaTimer:- ' + ex.message);
}
}, 1000);
} catch (ex) {
alert('WMMCPA|_playNow:- ' + ex.message);

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.

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

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

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 :-)

Resources