Hello There,
I am new to phonegap.I am trying to record a audio clip and uploading it to server.I am working with phonegap +jquery mobile + Android.Can anyone tell me a good way which can work for me with a small example.Basically I have a form which have a button as Record, from which user can record an audio clip and can publish it.So basically I need to upload that recorded file on server on submitting the form.I tried phonegap API's Media and File for recording and uploading file but couldn't succeed.
I am using following function for recording :
function recordAudio() {
var src = "myrecording.mp3";
var mediaRec = new Media(src, onSuccess, onError);
// Record audio
mediaRec.startRecord();
// Stop recording after 10 sec
var recTime = 0;
var recInterval = setInterval(function() {
recTime = recTime + 1;
setAudioPosition(recTime + " sec");
if (recTime >= 10) {
clearInterval(recInterval);
mediaRec.stopRecord();
}
}, 1000);
}
Now I need to upload this recorded file to server.I am testing on emulator.
Kind Regrads
Jaya
the default location of recorded audio for android is "mnt/sdcard/myrecording.wav"
to upload, use the FileTransfer object to upload the audio
var ft = new FileTransfer();
ft.upload("mnt/sdcard/myrecording.wav", "http://www.website.com/upload.php", win, fail);
Why don't you try the captureAudio function directly?
function captureAudio() {
// Launch device audio recorder
navigator.device.capture.captureAudio(captureSuccess, captureError);
}
Check here: PhoneGap Doc
Under captureSuccess callback, you could use the FileTransfer object to upload your file.
Related
I am developing a radio app using ionic creator.
audio play function works ok, but I need to pause to audio
Another question:
Double clicking to listen to two tunes at once?
this is audio play function,
function ($scope, $stateParams) {
$scope.playWebAudio = function(){
try{
$scope.audio = new Audio('Audio stream URL');
$scope.audio.play();
}
catch(e){
alert(e);
console.log(e);
}
}
play button
ng-click playWebAudio()
Strop Audio you have to use $cordovaMedia plugin instead of $cordovaNativeAudio
now you have to do like this:
module.controller('MyCtrl', function($scope, $cordovaMedia) {
var src = "/src/audio.mp3";
var media = $cordovaMedia.newMedia(src);
var iOSPlayOptions = {
numberOfLoops: 2,
playAudioWhenScreenIsLocked : false
}
media.play(iOSPlayOptions); // iOS only!
media.play(); // Android
media.pause();
media.stop();
media.release();
media.seekTo(5000); // milliseconds value
media.setVolume(0.5);
media.startRecord();
media.stopRecord();
media.getDuration();
media.getCurrentPosition().then(...);
});
for more detail refer to this tlink enter link description here
I've been stuck on this issue for awhile and i can't seem to find a solution. What i am trying to achieve is this:
Select a video from the phone's library
Upload the video to Amazon AWS using a signed PUT url
Download the uploaded video and play it back on the PC
I am able to select the video from the phone's gallery and successfully upload it to Amazon aws. However, when i try to open and playback the file, media player says that the file format is not supported.
It cannot be a codec issue with my player because i can playback other videos that were uploaded to amazon (via standard HTML file input). Plus, when i transfer the same video from my phone to the desktop, it is playable.
I have a feeling that i'm missing out something when setting up the FileTransfer object. Below is a snippet of my code:
navigator.camera.getPicture(
function(imgUrl) {
that.mDialogOpen("Uploading video...");
window.resolveLocalFileSystemURL(imgUrl, function(fileEntry) {
fileEntry.file(function(file) {
var parts = fileEntry.nativeURL.split('/');
var filename = parts[parts.length - 1];
// Params is sent to the server to generate the signed amazon put url
var params = {'a':'handlerFunctionKey', 'name':filename, 'type':'multipart/encrypted'};
var callback = function(data) {
alert("In callback");
var dataResp = data['handlerFunctionKey'];
if (dataResp.status == 'SUCCESS') {
var amazonUrl = decodeURIComponent(dataResp.object);
alert("Setting up options: " + file.type);
var ftOptions = new FileUploadOptions();
ftOptions.fileName = filename;
ftOptions.mimeType = file.type;
ftOptions.chunkedMode = false;
ftOptions.headers = {'Content-Type':"multipart/encrypted",'x-amz-acl':'public-read',"Connection":"close"};
ftOptions.httpMethod = 'PUT';
var ft = new FileTransfer();
ft.upload(imgUrl, amazonUrl,
function() {
$("#mModalText").html("Upload success");
},
function(err) {
alert("Upload error: " + err.code);
alert("Upload target: " + err.target);
alert("Upload source: " + err.source);
}, ftOptions, true);
}
};
that.doAjax(params, callback); // Execute ajax call to server and run the callback function upon response
}, function() {});
}, function() {});
},
function() {}, options);
The 'options' for the getPicture function are:
var options = {quality:50, destinationType:Camera.DestinationType.FILE_URI};
options['sourceType'] = Camera.PictureSourceType.PHOTOLIBRARY;
options['mediaType'] = Camera.MediaType.VIDEO;
options['targetWidth'] = 640;
options['targetHeight'] = 480;
The video i'm uploading is a MP4 with mimeType 'video/mp4'. I'm testing this on an Android. I'm building the code with Phonegap version 6.0.1 via remote build.
Thanks in advance.
I'm using the following code to record audio using Cordova Media plugin on android devices. This results in an empty audio file despite returning successfully on stopRecord(). Can somebody point to what might be wrong with this code?
$cordovaFile.createFile(cordova.file.dataDirectory, 'new-rec.amr'), false)
.then(function (fileObj) {
console.log('File created', fileObj);
var nativePath = fileObj.nativeURL;
resolveLocalFileSystemURL(nativePath, function (entry) {
var internalPath = entry.toInternalURL();
var mediaRec = new Media(internalPath,
//success callback
function (success) {
console.log("record success", success);
},
//error callback
function (err) {
console.log("record error: " + JSON.stringify(err));
});
// Start recording audio
mediaRec.startRecord();
});
}, function (error) {
console.log('Cannot create a file to initiate a new recording', error);
});
I was having this exact same problem today. Solved it by releasing the Media object. I'm not sure why this helped, but I have a feeling it may be that the OS is holding onto the Media object instead of saving it and then once it's released it's properly saved?
Not 100% sure though. It works without releasing in other Cordova directories (e.g. cordova.file.externalDataDirectory).
Here's my code:
var fileName = randomFileName();
fileName = fileName + ".aac";
var store = cordova.file.dataDirectory;
window.resolveLocalFileSystemURL(store, function(dir){
var directoryToSave = dir.nativeURL + fileName;
$scope.audioRecording = new Media(directoryToSave, audioRecordingSuccess, audioRecordingFail, audioStatus);
$scope.audioRecording.startRecord();
setTimeout(function(){
$scope.audioRecording.stopRecord();
$scope.audioRecording.release();
}, 5000);
});
So, i have made an app with phonegap build, where the goal is to read a xml file that contains info about audio tracks, and includes the path for each audio track.
I proceed to input the data of xml file into html, and before it was working fine. After i imported my project into phonegap build, no more audio plays. The controls work, but the audio doesn't play.
Here is the code:
<script>
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
}
}
}, true);
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","teste.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table><tr><th>Track</th><th>Description</th<th>URL</th></tr>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++){
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("DESCRIPTION")[0].childNodes[0].nodeValue);
document.write("</td><td>");
var audio = x[i].getElementsByTagName("URL")[0].childNodes[0].nodeValue;
document.write('<audio controls><source src="'+audio +'" type="audio/mpeg"></audio>');
document.write("</td></tr>");
}
document.write("</table>");
</script>
The XML file is simply structured like this:
<CD>
<TITLE>Track one</TITLE>
<DESCRIPTION>Bob Dylan</DESCRIPTION>
<URL>files/test.mp3</URL>
</CD>
I have read some similar questions and find that most mistakes are in the PATH of the audio file. What should i do for the audio to play?
Thanks
EDIT: I have updated my code:
var path = '/android_asset/www/';
var audio = x[i].getElementsByTagName("URL")[0].childNodes[0].nodeValue;
var audioPath = path+audio;
alert(audioPath);
document.write('PLAY<br/>');
document.write('PAUSE<br/>');
document.write('STOP');
document.write('<p id="audio_position"></p>');
The alert(audioPath) returns the correct path and it works when I use this function:
function onDeviceReady() {
playAudio('/android_asset/www/files/test1.mp3');
}
The audioPath is the same as the path above.
But the app doesn't play the sound when i press Play...
Any ideas?
playAudio function:
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);
}
}
FOUND my problem! It was the 'onclick'. I now import jQuery and built the following code:
$(".btPlay").on("click",function (e) {
// body...
console.log("Play");
playAudio(audioPath);
});
It now works!
Try to install the cordova Media plugin org.apache.cordova.media (http://docs.phonegap.com/en/edge/cordova_media_media.md.html)
And then, try this :
//src is your path to your file
var my_media = new Media(src, function(){
alert("Success");
}, function(){
alert("Fail");
});
my_media.play();
Try it with all the paths yuo already tried, but this plugin works for me with online files.
EDIT: You may need to add '/android_asset/www/' in front of your src
How does Media.release() work. Looking at the docs it feels that you have to use it like this:
MediaService.loadMedia('sounds/connection-error.wav').then(function(media){
media.play();
media.release();
});
But I googled enough to know that is wrong. We have to explicitly release the core instances on Android.
But how to do that? If I have 8 views in my app and if I play a sound file on each of those views does that count as 8 core instances being used? And can I go back to say view number 1 and again play the sound associated with that view? If so, would that count as a 9th instances ?
Straight away calling media.release() just like above does not play any sound at all.
Most common way to play sounds using Cordova Media plugin is following:
function playAudio(src) {
// HTML5 Audio
if (typeof Audio != "undefined") {
new Audio(src).play() ;
// Phonegap media
} else if (typeof device != "undefined") {
// Android needs the search path explicitly specified
if (device.platform == 'Android') {
src = '/android_asset/www/' + src;
}
var mediaRes = new Media(src,
function onSuccess() {
// release the media resource once finished playing
mediaRes.release();
},
function onError(e){
console.log("error playing sound: " + JSON.stringify(e));
});
mediaRes.play();
} else {
console.log("no sound API to play: " + src);
}
}