JavaScript Star Rating System - javascript

I have a working star rating system, but If a user has already voted and changes their mind on the vote, they cannot reset their vote.
Here is what I have in the Javascript:
<script type="text/javascript">
var set = false;
var v = 0;
var a;
function loadStars() {
star1 = new Image();
star1.src = "images/star1.png";
star2 = new Image();
star2.src = "images/star2.png";
}
function highlight(x) {
if (set == false) {
y = x * 1 + 1
switch (x) {
case "1":
document.getElementById(x).src = star2.src;
document.getElementById('vote').innerHTML = "One star";
break;
case "2":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Two stars"
break;
case "3":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Three stars"
break;
case "4":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Four stars"
break;
case "5":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Five stars"
break;
}
}
}
function losehighlight(x) {
if (set == false) {
for (i = 1; i < 6; i++) {
document.getElementById(i).src = star1.src;
document.getElementById('vote').innerHTML = ""
}
}
}
function setStar(x) {
y = x * 1 + 1
if (set == false) {
switch (x) {
case "1":
a = "1"
flash(a);
break;
case "2":
a = "2"
flash(a);
break;
case "3":
a = "3"
flash(a);
break;
case "4":
a = "4"
flash(a);
break;
case "5":
a = "5"
flash(a);
break;
}
set = true;
insertrating(x, '<?=$themeid?>');
document.getElementById('vote').innerHTML = "Thank you!";
}
function flash() {
y = a * 1 + 1
switch (v) {
case 0:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star1.src;
}
v = 1
setTimeout(flash, 200)
break;
case 1:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
v = 2
setTimeout(flash, 200)
break;
case 2:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star1.src;
}
v = 3
setTimeout(flash, 200)
break;
case 3:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
v = 4
setTimeout(flash, 200)
break;
case 4:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star1.src;
}
v = 5
setTimeout(flash, 200)
break;
case 5:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
v = 6
setTimeout(flash, 200)
break;
}
}
</script>
How would I go about allowing the user to resubmit a vote?
My html looks like this:
<span style="float: left; text-align: left;"> Rate This Theme<br />
<img src="images//star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="1" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="2" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="3" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="4" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="5" style="float: left;" />
</span>

As far as I can tell, the only thing preventing the user from re-voting is your set variable.
if (set==false)
{
...
set=true;
Just get rid of the if clause and it should run even if set==true
Per Tomalak's comment, i forgot to mention that:
If the backend doesn't support this,
then it will insert a new vote rather
than changing the existing one. And
since there doesn't appear to be any
user identification, that would appear
to be the case
If you don't have any user authentication, at least use a cookie or something to keep track of which user is what so that the vote is edited, not a new one created.
As for setting cookies, I'd recommend setting a cookie via Javascript once the user votes the first time. On the backend, whatever you're using for server-side technology should check to see if a cookie already exists, and if it does, edit the ranking entry instead of creating a new one.
Here's a good resource on cookies in JS: http://www.quirksmode.org/js/cookies.html

bootstrap V4 font-awesome pro jquery
$('.starts i').click(function(){
$('.starts i').removeClass('fas').addClass('fal');
var sindex=$('.starts i').index(this);
for(var i=0;i<=sindex;i++){
$('.starts i').eq(i).removeClass('fal').addClass('fas');
}
})
<div class="starts h4 mt-3" style="color:#FBC02D">
<span class=" ml-2"><i class="fal fa-star"></i></span>
<span class="checked ml-2 title"><i class="fal fa-star"></i></span>
<span class="checked ml-2"><i class="fal fa-star"></i></span>
<span class="checked ml-2"><i class="fal fa-star"></i></span>
<span class="checked ml-2"><i class="fal fa-star"></i></span>
</div>

Related

Javascript for card shuffle failing

Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}

Radio Buttons are being grouped while having different id's JavaScript

I am trying to create some questions where you can choose an option from 1 to 5.
I am doing this using radio buttons, and I also change their ID so that they are not the same entity.
Although I am first creating the first question and after the other one, for some reason all the radio buttons are connected and I can only choose 1 button out of the 10 if I create 2 questions, and not 1 from the first question and 1 from the next one.
Does anyone know how to fix this problem? Check my code below to see the problem. Thanks
This is my code:
const questionnaire = document.getElementById('questionaire');
var numsQN = 0;
questionnaire.onclick = ev => {
if (ev.target.tagName === "BUTTON") {
switch (ev.target.className) {
case "remove-qu":
switch (ev.target.parentNode.className) {
case "numQuestion":
numsQN--;
document.getElementById('numberOfNumQuestions').innerHTML = "Number Questions = " + numsQN;
break;
}
ev.target.parentNode.remove();
break;
case "add-numli":
newNumSubquestion(ev.target.closest(".starQuestion").querySelector('ul'), false)
break;
}
}
else {
switch (ev.target.className) {
case "remove-numli":
ev.target.parentNode.remove();
break;
}
}
}
function newNumQuestion() {
questionnaire.insertAdjacentHTML('beforeend', `
<div class='numQuestion'> <div class="numbers"> <ul></ul> </div>`);
}
function newNumSubquestion(q, subquestionNumber) {
q.insertAdjacentHTML('beforeend', `
<li class="numSubquestion">
<span class="numSubquestionName">Sub-question</span>
<div id='colourRadioButtons'> </div>`);
var element = document.getElementById("colourRadioButtons");
var newName = "colourRadioButtons" + subquestionNumber + "";
element.id = newName;
let lastRadio = false;
const numbers = { "5": false, "4": false, "3": false, "2": false, "1": false, },
radioStatic = {
name: "colour", onchange: (event) => {
if (lastRadio) {
numbers[lastRadio] = false;
}
lastRadio = event.currentTarget.value;
numbers[lastRadio] = event.currentTarget.checked;
}, type: "radio"
}; // radioStatic
for (let key in numbers) {
element.appendChild(
Object.assign(document.createElement("label"), { textContent: key })).appendChild(
Object.assign(document.createElement("input"), radioStatic, { checked: numbers[key], value: key }));
if (numbers[key]) {
lastRadio = key;
}
}
}
function generateNumberQuestion() {
let howManyOptionEachNumsQuestionHas = 2;
for (let i = 0; i < 1; i++) {
newNumQuestion(true);
for (let j = 0; j < howManyOptionEachNumsQuestionHas; j++) {
newNumSubquestion(questionnaire.querySelector("div.numQuestion:last-child ul"), j);
}
}
}
document.getElementById("addNumButton").onclick = function () { generateNumberQuestion(); };
<h1 id="myText" contenteditable="true">Survey Name</h1>
<button type="button" id="addNumButton">Number Rating</button>
<form>
<div id="questionaire"></div>
</form>

Making custom encryption with javascript (stuck in decrypt function)

I want to make new custom encryption engine with javascript, but i have a problem when i make a decryption function. In my decryption function I don't understand how to switch 3 characters to 1 character. In the decryption function section, 3 characters from the case I do not want are changing to the characters that are returned.
If you need my full code, i can share in here.
So please help me to solve this problem. Sorry for my bad English :)
<body>
<h3>Encrypt and Decrypt</h3>
<!-- Encrypt -->
<!-- <input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input"><br>
<button onclick="encrypt()">Encrypt</button> -->
<!-- Decrypt -->
<br><input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input2"><br>
<button onclick="decrypt()">Decrypt</button>
<!-- Result -->
<div id="result"></div>
<!-- Enginenya -->
<script>
function encrypt(){
var rawtext = document.getElementById("input").value;
var temptext = "";
for(i = 0; i < rawtext.length; i++){
temptext += enc(rawtext[i]);
}
document.getElementById("result").innerHTML = temptext;
}
function decrypt(){
var rawtext = document.getElementById("input2").value;
var temptext = "";
for(i = 0; i < rawtext.length; i++){
temptext += dec(rawtext[i]);
}
document.getElementById("result").innerHTML = temptext;
}
function enc(x){
switch(x){
case " " :
return " ";
break;
case "A" :
return "+/=";
break;
case "B" :
return "36=";
break;
}
}
function dec(x){
switch(x){
case "+/=" :
return "A";
break;
case "36=" :
return "B";
break;
}
}
</script>
</body>
You are looping through singular chars & passing them to dec(), eg. If you enter "+/=", you are actually calling dec('+') then dec('/') then dec('=')
When decrypting the entered value, you'll have to split them into groups of 3 & then pass those.
function decrypt(){
var rawtext = document.getElementById("input2").value;
var temptext = "";
for(i = 0, charsLength = rawtext.length; i < charsLength; i += 3){
temptext += dec(rawtext.substring(i, i + 3));
}
document.getElementById("result").innerHTML = temptext;
}
You could take three caracters for decrypting an encrypted string.
while (i < rawtext.length) {
temptext += dec(rawtext.slice(i, i += 3)); // take from index i and increment i by 3
}
function encrypt() {
var rawtext = document.getElementById("input").value,
temptext = "",
i;
for (i = 0; i < rawtext.length; i++) {
temptext += enc(rawtext[i]);
}
document.getElementById("result").innerHTML = temptext;
}
function decrypt() {
var rawtext = document.getElementById("input2").value,
temptext = "",
i = 0;
while (i < rawtext.length) {
temptext += dec(rawtext.slice(i, i += 3));
}
document.getElementById("result").innerHTML = temptext;
}
function enc(x) {
switch (x) {
case " ":
return " ";
case "A":
return "+/=";
case "B":
return "36=";
}
}
function dec(x) {
switch (x) {
case "+/=":
return "A";
case "36=":
return "B";
}
}
<h3>Encrypt and Decrypt</h3>
<input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input"><br>
<button onclick="encrypt()">Encrypt</button>
<!-- Decrypt -->
<br><input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input2"><br>
<button onclick="decrypt()">Decrypt</button>
<!-- Result -->
<div id="result"></div>
Looks like you're iterating over the text to decrypt character by character, but then your dec function expects three characters. This never happens, so dec() returns undefined.
Example:
decrypt("36=") ->
dec("3") + dec("6") + dec("=") ->
undefined + undefined + undefined
undefinedundefinedundefined
You should change your decrypt function to avoid this. Additionally, some pointers:
You don't initialise i in your encrypt/decrypt function
There's no need for a break; after a return in your case statements as return will end the execution.
Edit: Here's an example with map since some other answers had some with for loops. And also because I suspected it could be done with one line (and I was right!)
<body>
<h3>Encrypt and Decrypt</h3>
<br><input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input2"><br>
<button onclick="decrypt()">Decrypt</button>
<div id="result"></div>
<script>
function decrypt(){
document.getElementById("result").innerHTML = document.getElementById("input2").value.match(/.{1,3}/g).map(dec).join('');
}
function dec(x){
switch(x){
case "+/=" :
return "A";
case "36=" :
return "B";
default:
return "?";
}
}
</script>
</body>

How do I avoid overwriting when saving a recorded file to a site subfolder?

folks! I'm trying to implement an audio recorder within my website. I've just got to make the recorded file to be saved to a subfolder in my website (/speaking_audios). The main problem is that every recording savings I tested are being done with the same name: audio.wav. For example, I save a recent recording and there in the subfolder there appears a file named audio.wav, past three minutes I save another recording, just that this last one overwrites the first file I saved (as it is the same name).
recorder.php
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>FlashWavRecorder demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>FlashWavRecorder</h1>
<p><strong>Upload requires php, i.e. example will not work on github.com</strong></p>
<div id="recorder-audio" class="control_panel idle">
<button class="record_button" onclick="FWRecorder.record('audio', 'audio.wav');" title="Record">
<img src="images/record.png" alt="Record"/>
</button>
<button class="stop_recording_button" onclick="FWRecorder.stopRecording('audio');" title="Stop Recording">
<img src="images/stop.png" alt="Stop Recording"/>
</button>
<button class="play_button" onclick="FWRecorder.playBack('audio');" title="Play">
<img src="images/play.png" alt="Play"/>
</button>
<button class="pause_playing_button" onclick="FWRecorder.pausePlayBack('audio');" title="Pause Playing">
<img src="images/pause.png" alt="Pause Playing"/>
</button>
<button class="stop_playing_button" onclick="FWRecorder.stopPlayBack();" title="Stop Playing">
<img src="images/stop.png" alt="Stop Playing"/>
</button>
<div class="level"></div>
</div>
<div id="recorder-audio2" class="control_panel idle">
<button class="record_button" onclick="FWRecorder.record('audio2', 'audio2.wav');" title="Record">
<img src="images/record.png" alt="Record"/>
</button>
<button class="stop_recording_button" onclick="FWRecorder.stopRecording('audio2');" title="Stop Recording">
<img src="images/stop.png" alt="Stop Recording"/>
</button>
<button class="play_button" onclick="FWRecorder.playBack('audio2');" title="Play">
<img src="images/play.png" alt="Play"/>
</button>
<button class="pause_playing_button" onclick="FWRecorder.pausePlayBack('audio2');" title="Pause Playing">
<img src="images/pause.png" alt="Pause Playing"/>
</button>
<button class="stop_playing_button" onclick="FWRecorder.stopPlayBack();" title="Stop Playing">
<img src="images/stop.png" alt="Stop Playing"/>
</button>
<div class="level"></div>
</div>
<div class="details">
<button class="show_level" onclick="FWRecorder.observeLevel();">Show Level</button>
<button class="hide_level" onclick="FWRecorder.stopObservingLevel();" style="display: none;">Hide Level</button>
<span id="save_button">
<span id="flashcontent">
<p>Your browser must have JavaScript enabled and the Adobe Flash Player installed.</p>
</span>
</span>
<div><button class="show_settings" onclick="microphonePermission()">Microphone permission</button></div>
<div id="status">
Recorder Status...
</div>
<div>Duration: <span id="duration"></span></div>
<div>Activity Level: <span id="activity_level"></span></div>
<div>Upload status: <span id="upload_status"></span></div>
</div>
<form id="uploadForm" name="uploadForm" action="upload.php">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
<h4>Configure Microphone</h4>
<form class="mic_config" onsubmit="return false;">
<ul>
<li>
<label for="rate">Rate</label>
<select id="rate" name="rate">
<option value="44" selected>44,100 Hz</option>
<option value="22">22,050 Hz</option>
<option value="11">11,025 Hz</option>
<option value="8">8,000 Hz</option>
<option value="5">5,512 Hz</option>
</select>
</li>
<li>
<label for="gain">Gain</label>
<select id="gain" name="gain">
</select>
</li>
<li>
<label for="silenceLevel">Silence Level</label>
<select id="silenceLevel" name="silenceLevel">
</select>
</li>
<li>
<label for="silenceTimeout">Silence Timeout</label>
<input id="silenceTimeout" name="silenceTimeout" value="2000"/>
</li>
<li>
<input id="useEchoSuppression" name="useEchoSuppression" type="checkbox"/>
<label for="useEchoSuppression">Use Echo Suppression</label>
</li>
<li>
<input id="loopBack" name="loopBack" type="checkbox"/>
<label for="loopBack">Loop Back</label>
</li>
<li>
<button onclick="configureMicrophone();">Configure</button>
</li>
</ul>
</form>
</div>
</body>
</html>
upload.php
<?php
$save_folder = dirname(__FILE__) . "/speaking_audios";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = $_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\": $saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
?>
js/main.js
$(function () {
var $uploadStatus = $('#upload_status'),
$showLevelButton = $('.show_level'),
$hideLevelButton = $('.hide_level'),
$level = $('.control_panel .level');
var CLASS_CONTROLS = "control_panel";
var CLASS_RECORDING = "recording";
var CLASS_PLAYBACK_READY = "playback_ready";
var CLASS_PLAYING = "playing";
var CLASS_PLAYBACK_PAUSED = "playback_paused";
// Embedding flash object ---------------------------------------------------------------------------------------------
setUpFormOptions();
var appWidth = 24;
var appHeight = 24;
var flashvars = {'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "11.0.0", "", flashvars, params, attributes);
// Handling FWR events ------------------------------------------------------------------------------------------------
window.fwr_event_handler = function fwr_event_handler() {
$('#status').text("Last recorder event: " + arguments[0]);
var name, $controls;
switch (arguments[0]) {
case "ready":
var width = parseInt(arguments[1]);
var height = parseInt(arguments[2]);
FWRecorder.uploadFormId = "#uploadForm";
FWRecorder.uploadFieldName = "upload_file[filename]";
FWRecorder.connect("recorderApp", 0);
FWRecorder.recorderOriginalWidth = width;
FWRecorder.recorderOriginalHeight = height;
$('.save_button').css({'width': width, 'height': height});
break;
case "no_microphone_found":
break;
case "microphone_user_request":
recorderEl().addClass("floating");
FWRecorder.showPermissionWindow();
break;
case "microphone_connected":
FWRecorder.isReady = true;
$uploadStatus.css({'color': '#000'});
break;
case "permission_panel_closed":
FWRecorder.defaultSize();
recorderEl().removeClass("floating");
break;
case "microphone_activity":
$('#activity_level').text(arguments[1]);
break;
case "recording":
name = arguments[1];
$controls = controlsEl(name);
FWRecorder.hide();
setControlsClass($controls, CLASS_RECORDING);
break;
case "recording_stopped":
name = arguments[1];
$controls = controlsEl(name);
var duration = arguments[2];
FWRecorder.show();
setControlsClass($controls, CLASS_PLAYBACK_READY);
$('#duration').text(duration.toFixed(4) + " seconds");
break;
case "microphone_level":
$level.css({width: arguments[1] * 50 + '%'});
break;
case "observing_level":
$showLevelButton.hide();
$hideLevelButton.show();
break;
case "observing_level_stopped":
$showLevelButton.show();
$hideLevelButton.hide();
$level.css({width: 0});
break;
case "playing":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYING);
break;
case "playback_started":
name = arguments[1];
var latency = arguments[2];
break;
case "stopped":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYBACK_READY);
break;
case "playing_paused":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYBACK_PAUSED);
break;
case "save_pressed":
FWRecorder.updateForm();
break;
case "saving":
name = arguments[1];
break;
case "saved":
name = arguments[1];
var data = $.parseJSON(arguments[2]);
if (data.saved) {
$('#upload_status').css({'color': '#0F0'}).text(name + " was saved");
} else {
$('#upload_status').css({'color': '#F00'}).text(name + " was not saved");
}
break;
case "save_failed":
name = arguments[1];
var errorMessage = arguments[2];
$uploadStatus.css({'color': '#F00'}).text(name + " failed: " + errorMessage);
break;
case "save_progress":
name = arguments[1];
var bytesLoaded = arguments[2];
var bytesTotal = arguments[3];
$uploadStatus.css({'color': '#000'}).text(name + " progress: " + bytesLoaded + " / " + bytesTotal);
break;
}
};
// Helper functions ---------------------------------------------------------------------------------------------------
function setUpFormOptions() {
var gain = $('#gain')[0];
var silenceLevel = $('#silenceLevel')[0];
for (var i = 0; i <= 100; i++) {
gain.options[gain.options.length] = new Option(100 - i);
silenceLevel.options[silenceLevel.options.length] = new Option(i);
}
}
function setControlsClass($controls, className) {
$controls.attr('class', CLASS_CONTROLS + ' ' + className);
}
function controlsEl(name) {
return $('#recorder-' + name);
}
function recorderEl() {
return $('#recorderApp');
}
// Button actions -----------------------------------------------------------------------------------------------------
window.microphonePermission = function () {
recorderEl().addClass("floating");
FWRecorder.showPermissionWindow({permanent: true});
};
window.configureMicrophone = function () {
if (!FWRecorder.isReady) {
return;
}
FWRecorder.configure($('#rate').val(), $('#gain').val(), $('#silenceLevel').val(), $('#silenceTimeout').val());
FWRecorder.setUseEchoSuppression($('#useEchoSuppression').is(":checked"));
FWRecorder.setLoopBack($('#loopBack').is(":checked"));
};
});
js/recorder.js
(function(global) {
var Recorder;
var RECORDED_AUDIO_TYPE = "audio/wav";
Recorder = {
recorder: null,
recorderOriginalWidth: 0,
recorderOriginalHeight: 0,
uploadFormId: null,
uploadFieldName: null,
isReady: false,
connect: function(name, attempts) {
if(navigator.appName.indexOf("Microsoft") != -1) {
Recorder.recorder = window[name];
} else {
Recorder.recorder = document[name];
}
if(attempts >= 40) {
return;
}
// flash app needs time to load and initialize
if(Recorder.recorder && Recorder.recorder.init) {
Recorder.recorderOriginalWidth = Recorder.recorder.width;
Recorder.recorderOriginalHeight = Recorder.recorder.height;
if(Recorder.uploadFormId && $) {
var frm = $(Recorder.uploadFormId);
Recorder.recorder.init(frm.attr('action').toString(), Recorder.uploadFieldName, frm.serializeArray());
}
return;
}
setTimeout(function() {Recorder.connect(name, attempts+1);}, 100);
},
playBack: function(name) {
// TODO: Rename to `playback`
Recorder.recorder.playBack(name);
},
pausePlayBack: function(name) {
// TODO: Rename to `pausePlayback`
Recorder.recorder.pausePlayBack(name);
},
playBackFrom: function(name, time) {
// TODO: Rename to `playbackFrom`
Recorder.recorder.playBackFrom(name, time);
},
record: function(name, filename) {
Recorder.recorder.record(name, filename);
},
stopRecording: function() {
Recorder.recorder.stopRecording();
},
stopPlayBack: function() {
// TODO: Rename to `stopPlayback`
Recorder.recorder.stopPlayBack();
},
observeLevel: function() {
Recorder.recorder.observeLevel();
},
stopObservingLevel: function() {
Recorder.recorder.stopObservingLevel();
},
observeSamples: function() {
Recorder.recorder.observeSamples();
},
stopObservingSamples: function() {
Recorder.recorder.stopObservingSamples();
},
resize: function(width, height) {
Recorder.recorder.width = width + "px";
Recorder.recorder.height = height + "px";
},
defaultSize: function() {
Recorder.resize(Recorder.recorderOriginalWidth, Recorder.recorderOriginalHeight);
},
show: function() {
Recorder.recorder.show();
},
hide: function() {
Recorder.recorder.hide();
},
duration: function(name) {
// TODO: rename to `getDuration`
return Recorder.recorder.duration(name || Recorder.uploadFieldName);
},
getBase64: function(name) {
var data = Recorder.recorder.getBase64(name);
return 'data:' + RECORDED_AUDIO_TYPE + ';base64,' + data;
},
getBlob: function(name) {
var base64Data = Recorder.getBase64(name).split(',')[1];
return base64toBlob(base64Data, RECORDED_AUDIO_TYPE);
},
getCurrentTime: function(name) {
return Recorder.recorder.getCurrentTime(name);
},
isMicrophoneAccessible: function() {
return Recorder.recorder.isMicrophoneAccessible();
},
updateForm: function() {
var frm = $(Recorder.uploadFormId);
Recorder.recorder.update(frm.serializeArray());
},
showPermissionWindow: function(options) {
Recorder.resize(240, 160);
// need to wait until app is resized before displaying permissions screen
var permissionCommand = function() {
if (options && options.permanent) {
Recorder.recorder.permitPermanently();
} else {
Recorder.recorder.permit();
}
};
setTimeout(permissionCommand, 1);
},
configure: function(rate, gain, silenceLevel, silenceTimeout) {
rate = parseInt(rate || 22);
gain = parseInt(gain || 100);
silenceLevel = parseInt(silenceLevel || 0);
silenceTimeout = parseInt(silenceTimeout || 4000);
switch(rate) {
case 44:
case 22:
case 11:
case 8:
case 5:
break;
default:
throw("invalid rate " + rate);
}
if(gain < 0 || gain > 100) {
throw("invalid gain " + gain);
}
if(silenceLevel < 0 || silenceLevel > 100) {
throw("invalid silenceLevel " + silenceLevel);
}
if(silenceTimeout < -1) {
throw("invalid silenceTimeout " + silenceTimeout);
}
Recorder.recorder.configure(rate, gain, silenceLevel, silenceTimeout);
},
setUseEchoSuppression: function(val) {
if(typeof(val) != 'boolean') {
throw("invalid value for setting echo suppression, val: " + val);
}
Recorder.recorder.setUseEchoSuppression(val);
},
setLoopBack: function(val) {
if(typeof(val) != 'boolean') {
throw("invalid value for setting loop back, val: " + val);
}
Recorder.recorder.setLoopBack(val);
}
};
function base64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: contentType});
}
global.FWRecorder = Recorder;
})(this);
I couldn't expose all the files above, cause there was no more space left. Well, I just want to individualize each saved file. It can be that way: username.randomidcode or something like that.

how to upload a recorded audio file using pdo to a website folder

I am trying to implement an audio recorder within my website. What I want is to make the user save the recorded file directly to the database and/or to a subfolder in my website (called /speaking_audios). There follows the main files: recorder.php, sync.html, upload.php, js/main.js, js/swfobject.js, js/recorder.js, recorder.swf (I don't know what it is for).
recorder.php
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>FlashWavRecorder demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>FlashWavRecorder</h1>
<p><strong>Upload requires php, i.e. example will not work on github.com</strong></p>
<div id="recorder-audio" class="control_panel idle">
<button class="record_button" onclick="FWRecorder.record('audio', 'audio.wav');" title="Record">
<img src="images/record.png" alt="Record"/>
</button>
<button class="stop_recording_button" onclick="FWRecorder.stopRecording('audio');" title="Stop Recording">
<img src="images/stop.png" alt="Stop Recording"/>
</button>
<button class="play_button" onclick="FWRecorder.playBack('audio');" title="Play">
<img src="images/play.png" alt="Play"/>
</button>
<button class="pause_playing_button" onclick="FWRecorder.pausePlayBack('audio');" title="Pause Playing">
<img src="images/pause.png" alt="Pause Playing"/>
</button>
<button class="stop_playing_button" onclick="FWRecorder.stopPlayBack();" title="Stop Playing">
<img src="images/stop.png" alt="Stop Playing"/>
</button>
<div class="level"></div>
</div>
<div id="recorder-audio2" class="control_panel idle">
<button class="record_button" onclick="FWRecorder.record('audio2', 'audio2.wav');" title="Record">
<img src="images/record.png" alt="Record"/>
</button>
<button class="stop_recording_button" onclick="FWRecorder.stopRecording('audio2');" title="Stop Recording">
<img src="images/stop.png" alt="Stop Recording"/>
</button>
<button class="play_button" onclick="FWRecorder.playBack('audio2');" title="Play">
<img src="images/play.png" alt="Play"/>
</button>
<button class="pause_playing_button" onclick="FWRecorder.pausePlayBack('audio2');" title="Pause Playing">
<img src="images/pause.png" alt="Pause Playing"/>
</button>
<button class="stop_playing_button" onclick="FWRecorder.stopPlayBack();" title="Stop Playing">
<img src="images/stop.png" alt="Stop Playing"/>
</button>
<div class="level"></div>
</div>
<div class="details">
<button class="show_level" onclick="FWRecorder.observeLevel();">Show Level</button>
<button class="hide_level" onclick="FWRecorder.stopObservingLevel();" style="display: none;">Hide Level</button>
<span id="save_button">
<span id="flashcontent">
<p>Your browser must have JavaScript enabled and the Adobe Flash Player installed.</p>
</span>
</span>
<div><button class="show_settings" onclick="microphonePermission()">Microphone permission</button></div>
<div id="status">
Recorder Status...
</div>
<div>Duration: <span id="duration"></span></div>
<div>Activity Level: <span id="activity_level"></span></div>
<div>Upload status: <span id="upload_status"></span></div>
</div>
<form id="uploadForm" name="uploadForm" action="upload.php">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
<h4>Configure Microphone</h4>
<form class="mic_config" onsubmit="return false;">
<ul>
<li>
<label for="rate">Rate</label>
<select id="rate" name="rate">
<option value="44" selected>44,100 Hz</option>
<option value="22">22,050 Hz</option>
<option value="11">11,025 Hz</option>
<option value="8">8,000 Hz</option>
<option value="5">5,512 Hz</option>
</select>
</li>
<li>
<label for="gain">Gain</label>
<select id="gain" name="gain">
</select>
</li>
<li>
<label for="silenceLevel">Silence Level</label>
<select id="silenceLevel" name="silenceLevel">
</select>
</li>
<li>
<label for="silenceTimeout">Silence Timeout</label>
<input id="silenceTimeout" name="silenceTimeout" value="2000"/>
</li>
<li>
<input id="useEchoSuppression" name="useEchoSuppression" type="checkbox"/>
<label for="useEchoSuppression">Use Echo Suppression</label>
</li>
<li>
<input id="loopBack" name="loopBack" type="checkbox"/>
<label for="loopBack">Loop Back</label>
</li>
<li>
<button onclick="configureMicrophone();">Configure</button>
</li>
</ul>
</form>
</div>
</body>
</html>
upload.php
<?php
$save_folder = dirname(__FILE__) . "/speaking_audios";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = $_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\": $saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
?>
js/main.js
$(function () {
var $uploadStatus = $('#upload_status'),
$showLevelButton = $('.show_level'),
$hideLevelButton = $('.hide_level'),
$level = $('.control_panel .level');
var CLASS_CONTROLS = "control_panel";
var CLASS_RECORDING = "recording";
var CLASS_PLAYBACK_READY = "playback_ready";
var CLASS_PLAYING = "playing";
var CLASS_PLAYBACK_PAUSED = "playback_paused";
// Embedding flash object ---------------------------------------------------------------------------------------------
setUpFormOptions();
var appWidth = 24;
var appHeight = 24;
var flashvars = {'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "11.0.0", "", flashvars, params, attributes);
// Handling FWR events ------------------------------------------------------------------------------------------------
window.fwr_event_handler = function fwr_event_handler() {
$('#status').text("Last recorder event: " + arguments[0]);
var name, $controls;
switch (arguments[0]) {
case "ready":
var width = parseInt(arguments[1]);
var height = parseInt(arguments[2]);
FWRecorder.uploadFormId = "#uploadForm";
FWRecorder.uploadFieldName = "upload_file[filename]";
FWRecorder.connect("recorderApp", 0);
FWRecorder.recorderOriginalWidth = width;
FWRecorder.recorderOriginalHeight = height;
$('.save_button').css({'width': width, 'height': height});
break;
case "no_microphone_found":
break;
case "microphone_user_request":
recorderEl().addClass("floating");
FWRecorder.showPermissionWindow();
break;
case "microphone_connected":
FWRecorder.isReady = true;
$uploadStatus.css({'color': '#000'});
break;
case "permission_panel_closed":
FWRecorder.defaultSize();
recorderEl().removeClass("floating");
break;
case "microphone_activity":
$('#activity_level').text(arguments[1]);
break;
case "recording":
name = arguments[1];
$controls = controlsEl(name);
FWRecorder.hide();
setControlsClass($controls, CLASS_RECORDING);
break;
case "recording_stopped":
name = arguments[1];
$controls = controlsEl(name);
var duration = arguments[2];
FWRecorder.show();
setControlsClass($controls, CLASS_PLAYBACK_READY);
$('#duration').text(duration.toFixed(4) + " seconds");
break;
case "microphone_level":
$level.css({width: arguments[1] * 50 + '%'});
break;
case "observing_level":
$showLevelButton.hide();
$hideLevelButton.show();
break;
case "observing_level_stopped":
$showLevelButton.show();
$hideLevelButton.hide();
$level.css({width: 0});
break;
case "playing":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYING);
break;
case "playback_started":
name = arguments[1];
var latency = arguments[2];
break;
case "stopped":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYBACK_READY);
break;
case "playing_paused":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYBACK_PAUSED);
break;
case "save_pressed":
FWRecorder.updateForm();
break;
case "saving":
name = arguments[1];
break;
case "saved":
name = arguments[1];
var data = $.parseJSON(arguments[2]);
if (data.saved) {
$('#upload_status').css({'color': '#0F0'}).text(name + " was saved");
} else {
$('#upload_status').css({'color': '#F00'}).text(name + " was not saved");
}
break;
case "save_failed":
name = arguments[1];
var errorMessage = arguments[2];
$uploadStatus.css({'color': '#F00'}).text(name + " failed: " + errorMessage);
break;
case "save_progress":
name = arguments[1];
var bytesLoaded = arguments[2];
var bytesTotal = arguments[3];
$uploadStatus.css({'color': '#000'}).text(name + " progress: " + bytesLoaded + " / " + bytesTotal);
break;
}
};
// Helper functions ---------------------------------------------------------------------------------------------------
function setUpFormOptions() {
var gain = $('#gain')[0];
var silenceLevel = $('#silenceLevel')[0];
for (var i = 0; i <= 100; i++) {
gain.options[gain.options.length] = new Option(100 - i);
silenceLevel.options[silenceLevel.options.length] = new Option(i);
}
}
function setControlsClass($controls, className) {
$controls.attr('class', CLASS_CONTROLS + ' ' + className);
}
function controlsEl(name) {
return $('#recorder-' + name);
}
function recorderEl() {
return $('#recorderApp');
}
// Button actions -----------------------------------------------------------------------------------------------------
window.microphonePermission = function () {
recorderEl().addClass("floating");
FWRecorder.showPermissionWindow({permanent: true});
};
window.configureMicrophone = function () {
if (!FWRecorder.isReady) {
return;
}
FWRecorder.configure($('#rate').val(), $('#gain').val(), $('#silenceLevel').val(), $('#silenceTimeout').val());
FWRecorder.setUseEchoSuppression($('#useEchoSuppression').is(":checked"));
FWRecorder.setLoopBack($('#loopBack').is(":checked"));
};
});
js/recorder.js
(function(global) {
var Recorder;
var RECORDED_AUDIO_TYPE = "audio/wav";
Recorder = {
recorder: null,
recorderOriginalWidth: 0,
recorderOriginalHeight: 0,
uploadFormId: null,
uploadFieldName: null,
isReady: false,
connect: function(name, attempts) {
if(navigator.appName.indexOf("Microsoft") != -1) {
Recorder.recorder = window[name];
} else {
Recorder.recorder = document[name];
}
if(attempts >= 40) {
return;
}
// flash app needs time to load and initialize
if(Recorder.recorder && Recorder.recorder.init) {
Recorder.recorderOriginalWidth = Recorder.recorder.width;
Recorder.recorderOriginalHeight = Recorder.recorder.height;
if(Recorder.uploadFormId && $) {
var frm = $(Recorder.uploadFormId);
Recorder.recorder.init(frm.attr('action').toString(), Recorder.uploadFieldName, frm.serializeArray());
}
return;
}
setTimeout(function() {Recorder.connect(name, attempts+1);}, 100);
},
playBack: function(name) {
// TODO: Rename to `playback`
Recorder.recorder.playBack(name);
},
pausePlayBack: function(name) {
// TODO: Rename to `pausePlayback`
Recorder.recorder.pausePlayBack(name);
},
playBackFrom: function(name, time) {
// TODO: Rename to `playbackFrom`
Recorder.recorder.playBackFrom(name, time);
},
record: function(name, filename) {
Recorder.recorder.record(name, filename);
},
stopRecording: function() {
Recorder.recorder.stopRecording();
},
stopPlayBack: function() {
// TODO: Rename to `stopPlayback`
Recorder.recorder.stopPlayBack();
},
observeLevel: function() {
Recorder.recorder.observeLevel();
},
stopObservingLevel: function() {
Recorder.recorder.stopObservingLevel();
},
observeSamples: function() {
Recorder.recorder.observeSamples();
},
stopObservingSamples: function() {
Recorder.recorder.stopObservingSamples();
},
resize: function(width, height) {
Recorder.recorder.width = width + "px";
Recorder.recorder.height = height + "px";
},
defaultSize: function() {
Recorder.resize(Recorder.recorderOriginalWidth, Recorder.recorderOriginalHeight);
},
show: function() {
Recorder.recorder.show();
},
hide: function() {
Recorder.recorder.hide();
},
duration: function(name) {
// TODO: rename to `getDuration`
return Recorder.recorder.duration(name || Recorder.uploadFieldName);
},
getBase64: function(name) {
var data = Recorder.recorder.getBase64(name);
return 'data:' + RECORDED_AUDIO_TYPE + ';base64,' + data;
},
getBlob: function(name) {
var base64Data = Recorder.getBase64(name).split(',')[1];
return base64toBlob(base64Data, RECORDED_AUDIO_TYPE);
},
getCurrentTime: function(name) {
return Recorder.recorder.getCurrentTime(name);
},
isMicrophoneAccessible: function() {
return Recorder.recorder.isMicrophoneAccessible();
},
updateForm: function() {
var frm = $(Recorder.uploadFormId);
Recorder.recorder.update(frm.serializeArray());
},
showPermissionWindow: function(options) {
Recorder.resize(240, 160);
// need to wait until app is resized before displaying permissions screen
var permissionCommand = function() {
if (options && options.permanent) {
Recorder.recorder.permitPermanently();
} else {
Recorder.recorder.permit();
}
};
setTimeout(permissionCommand, 1);
},
configure: function(rate, gain, silenceLevel, silenceTimeout) {
rate = parseInt(rate || 22);
gain = parseInt(gain || 100);
silenceLevel = parseInt(silenceLevel || 0);
silenceTimeout = parseInt(silenceTimeout || 4000);
switch(rate) {
case 44:
case 22:
case 11:
case 8:
case 5:
break;
default:
throw("invalid rate " + rate);
}
if(gain < 0 || gain > 100) {
throw("invalid gain " + gain);
}
if(silenceLevel < 0 || silenceLevel > 100) {
throw("invalid silenceLevel " + silenceLevel);
}
if(silenceTimeout < -1) {
throw("invalid silenceTimeout " + silenceTimeout);
}
Recorder.recorder.configure(rate, gain, silenceLevel, silenceTimeout);
},
setUseEchoSuppression: function(val) {
if(typeof(val) != 'boolean') {
throw("invalid value for setting echo suppression, val: " + val);
}
Recorder.recorder.setUseEchoSuppression(val);
},
setLoopBack: function(val) {
if(typeof(val) != 'boolean') {
throw("invalid value for setting loop back, val: " + val);
}
Recorder.recorder.setLoopBack(val);
}
};
function base64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: contentType});
}
global.FWRecorder = Recorder;
})(this);
Well, I just want you to concentrate on the upload.php file and see what I'm doing wrong.
When dealing with files, a valid enctype and a POST method is required.
Therefore, you need to change this form:
<form id="uploadForm" name="uploadForm" action="upload.php">
To this:
<form enctype="multipart/form-data" method="post" id="uploadForm" name="uploadForm" action="upload.php">
and check for errors and making sure the folder you're uploading to, has the right permissions.
References:
http://php.net/manual/en/features.file-upload.post-method.php
http://php.net/manual/en/function.error-reporting.php

Categories