I've made an upload using JavaScript, PHP and Cordova. Everything works fine. But when I try to open the uploaded mp3 in browser or a desktop player like Windows Media Player, it says the file is corrupt. Any idea why this is happening?
I also have to say that when I inspect the corrupted file in browser it has video tags instead of audio tags.
My code:
//method to upload the audio
function uploadAudio(recordedSrc) {
var win = function(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
var fail = function(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = "recordupload.mp3";
options.mimeType = "audio/mpeg";
console.log(options);
var ft = new FileTransfer();
console.log(ft);
console.log(recordedSrc);
ft.upload(recordedSrc, encodeURI(app_url + "json/upload.php"), win, fail, options);
}
$('.upload').on('click', function(e) {
e.preventDefault();
//Method to upload Audio file to server
uploadAudio(mediaRecSrc);
});
Server side handling script in PHP:
<?php
// Where the file is going to be placed
$target_path = dirname(__FILE__) . "/uploaded_records/";
if (!file_exists($target_path)) {
mkdir ($target_path, 0777);
}
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['file']['name']);
$path = $_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
var_dump("ext is: " . $ext);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['file']['name']);
echo "target_path: " .$target_path;
}
?>
UPDATE:
It seems that the problem lies within the file(which on android works playing). I copied the file through usb device and tried playing it and there is the same problem, the file won't play. I have to say that the file is recorded using the media plugin from cordova. Maybe this is the problem, right?
SECOND UPDATE:
I recorded and uploaded a file as an .amr
format and converted it to .mp3
online here and the sound works. Any idea on how to resolve this problem?