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
Related
I have created a sound app for Android using Cordova. Everything was perfect, at least in the Android Studio's emulator, until I found something strange happening while testing on a real device.
My app contains more than 100 sounds one second each. You click to play sounds till you get 32 clicks that play audios without problems. But starting from thirty-third (33rd) click I get a message error:
code: -19 message: undefined
I must mention that you can reply the previous clicked sounds that still work. But other sounds get the error above.
If I close and reopen the app, sounds that gave error work again until I get to 33rd click and start getting the error message even for sounds that used to work.
Here is the code I use to play my sounds:
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var my_media = new playAudio();
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
my_media = {}; // init the play object
function playAudio(src, id) {
if (!my_media[id]) { // check if media already created
my_media[id] = new Media(src, onSuccess, onError);
}
my_media[id].play();
}
//playAudio('file:///android_asset/www/media/1.mp3');
// 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;
}
Any IDEA?
thanks
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);
});
I'm making a app with several audio files, but it won't play on the phone. It won't work even without /android_asset/www/.
Here's my code:
<script>
var at_du_bruger_det = new Audio('/android_asset/www/sound/at_du_bruger_det.wav');
</script>
<div class="swipebox portfolio-wide-item" onclick="at_du_bruger_det.play();">
<h3>At du bruger det</h3>
<p>Tryk for at afspille</p>
<div class="overlay"></div>
<img class="responsive-image" src="images/at_du_bruger_det.jpg" alt="img">
</div>
I've added the org.apache.cordova.media plugin to the config file.
If you look at the Cordova Media plugin documentation, you can see that a Media object is required:
// Play audio
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();
}
im trying to record an audio file using Media object in phonegap and then play it. i have no problem recording, but then when i try to play it my app shuts down, both on my emulator and my device. on the logcat it says: "null pointer exception at org.apache.cordova.readyPlayer (AudioPlayer.java)". many thanks to anyone who is willing to help me, it took me a while to realize im completely lost here.
here is the code which i copied from http://docs.phonegap.com/en/2.4.0/cordova_media_media.md.html#media.stopRecord and added .play() after the .stopRecord(). i can add the manifest and activity if needed, i doubt that the problem is there but i could be wrong.
index.html:
<script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Record audio
//
function recordAudio() {
var src = "myrecording.amr";
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();
document.getElementById('audio_position').innerHTML = "finished";
**mediaRec.play();**
}
}, 1000);
}
// Cordova is ready
//
function onDeviceReady() {
recordAudio();
}
// onSuccess Callback
//
function onSuccess() {
console.log("recordAudio():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>
<p id="media">Recording audio...</p>
<p id="audio_position"></p>
yuval
I found the same issue with Cordova 3.5 (with Media plugin 0.2.11) and Android 4.4. The solution is as described above. Basically something like this should do the trick:
mediaRec.stopRecord();
src = mediaRec.src; // if you don't have src defined anymore
mediaRec.release();
mediaPlay = new Media(src, onSuccess, onError);
mediaPlay.play();
There is no need to create an other Media object to play the previously recorded file. Just do the following - you have to release the media object after recording is stopped:
// variable in global scope
var mediaRec = 0;
// function to record an audio
function recordAudio() {
// create media object for your recording
mediaRec = new Media("phonegap_rec.amr", onMediaRecordSuccess, onMediaRecordError);
// start recording
mediaRec.startRecord();
// recording for 5 seconds
var recTime = 0;
var recInterval = setInterval(function() {
recTime = recTime + 1;
if (recTime >= 5) {
clearInterval(recInterval);
// stop recording after 5 seconds
mediaRec.stopRecord();
// release the media object (THIS IS THE KEY SOLUTION HERE)
mediaRec.release();
}
}, 1000);
}
// function to playback recorded audio
function playRecord() {
// check if the object exists
if (mediaRec) {
// now you can playback the recording
mediaRec.play();
}
}