我正在录制一个音频文件,并希望在后面的代码中使用php将该文件上传到一个文件夹,因为该文件夹在服务器上。这是我的PHP代码:
<?php
if(!is_dir("upload")){
$res = mkdir("upload",0777);
}
// pull the raw binary data from the POST array
$data = substr($_POST['bufferFile'], strpos($_POST['bufferFile'], ",") + 1);
//echo($data);
// decode it
$decodedData = base64_decode($data);
echo($decodedData);
//echo ($decodedData);
$filename = $_POST['fname'];
echo($filename);
// write the data out to the file
$fp = fopen('upload/'.$filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
这是javascript代码:
var reader = new FileReader();
var bufferFile;
var d = new Date();
var fileName = 'audio_recording_' + d.getMilliseconds() +'.wav';
reader.onload = function (event) {
bufferFile = event.target.result;
bufferFile = dataURItoArrayBuffer(bufferFile);
postData(function() {
var fd = new FormData();
fd.append('fname', fileName);
fd.append('bufferFile', bufferFile);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
}
});
});
};
reader.readAsDataURL(blob);
这是转换音频文件的功能:
function dataURItoArrayBuffer(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return ia;
}
文件上传到文件夹但数据已损坏,因为当我尝试使用媒体播放器打开上传的文件时,它会出现以下错误:
Windows Media Player无法播放该文件。播放器可能不支持该文件类型,或者可能不支持用于压缩文件的编解码器。 怎么了?