/    Sign up×
Community /Pin to ProfileBookmark

chat room, send audio to store in server

According to I make a website for chat and I want to send voice to communicate.

so I use this script from https://blog.addpipe.com/using-recorder-js-to-capture-wav-audio-in-your-html5-web-site/

This is javascript

[code]function createDownloadLink(blob) {
//name of .wav file to use during upload and download (without extendion)
var filename = new Date().toISOString();

console.log(‘bob = ‘ + typeof(blob));
console.log(‘file name = ‘ + typeof(filename));
var fd=new FormData();
fd.append(“audio_data”,blob, filename);

$.ajax({

url: “../func/upload.php”,
method: “POST”,
processData: false,
contentType: false,
data: fd,
enctype: ‘multipart/form-data’,
success: function (data) {
console.log(‘SUCCESS’ + data);
},
error: function (err) {
}
});
}[/code]

and this is server side PHP

[code]

//this will print out the received name, temp name, type, size, etc.
print_r($_FILES);
$input = str_replace(“:”,”_”,$_FILES[‘audio_data’][‘tmp_name’]); //get the temporary name that PHP gave to the uploaded file
$output = $_FILES[‘audio_data’][‘name’].”.wav”; //letting the client control the filename is a rather bad idea
//move the file from temp name to local folder using $output name
move_uploaded_file($input, $output);
[/code]

This is the print output

[code]
Array
(
[audio_data] => Array
(
[name] => 2021-07-02T07:59:33.877Z
[type] => audio/wav
[tmp_name] => C:xampptmpphpF3C8.tmp
[error] => 0
[size] => 44
)
)
[/code]

It seem no any error but I don’t find any file on the server.

Could you please kindly help me check?

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@tomcurry22Jul 02.2021 — Thanks for share high valuable article with us.

**Links removed by Site Administrator so it doesn't look like you're spamming us. Please don't post them again.**
Copy linkTweet thisAlerts:
@NitiphoneauthorJul 02.2021 — @tomcurry22#1633634 How can I upload the file to server?
Copy linkTweet thisAlerts:
@NogDogJul 02.2021 — Looks like this line would potentially change the name of the file it's going to look for in the move_uploaded_file() command after it:

<CODE lang="php">[code=php]$input = str_replace(":","_",$_FILES['audio_data']['tmp_name']);[/code]</CODE>

I would either remove it, or if you want to use <C>
$name</C> later, then just use the <C>$_FILES['audio_data']['tmp_name']</C> as the first argument for <C>move_uploaded_file()`.
Copy linkTweet thisAlerts:
@NitiphoneauthorJul 02.2021 — @NogDog#1633641 Actually I tried the same as you said from begining. but PHP said file not work.
[code]//this will print out the received name, temp name, type, size, etc.
$input = str_replace(":","_",$_FILES['audio_data']['tmp_name']); //get the temporary name that PHP gave to the uploaded file
$output = $_FILES['audio_data']['name'].".wav"; //letting the client control the filename is a rather bad idea
//move the file from temp name to local folder using $output name
$result = move_uploaded_file($input, $output);

echo "Result = [" . $result . "]";[/cpde]

From these code, the result is "Result = []"
Copy linkTweet thisAlerts:
@NitiphoneauthorJul 03.2021 — But the file I created it's no sound, it's like empty file always 44K

//this will print out the received name, temp name, type, size, etc.
$input = $_FILES['audio_data']['tmp_name']; //get the temporary name that PHP gave to the uploaded file
$output = "../management/design/voices/" . time() . uniqid() .".wav"; //letting the client control the filename is a rather bad idea
//move the file from temp name to local folder using $output name
$result = move_uploaded_file($input, $output);
Copy linkTweet thisAlerts:
@NitiphoneauthorJul 03.2021 — This is the javascript function to stop record
function stopRecording() {

<i> </i>
<i> </i>//tell the recorder to stop the recording
<i> </i>rec.stop();

<i> </i>//stop microphone access
<i> </i>gumStream.getAudioTracks()[0].stop();

<i> </i>//create the wav blob and pass it on to createDownloadLink
<i> </i>rec.exportWAV(createDownloadLink);
}

async function createDownloadLink(blob) {


<i> </i>var filename = new Date().toISOString();
<i> </i> var fd=new FormData();
<i> </i> fd.append('audio_data', blob,filename);
<i> </i> $.ajax({
<i> </i> url: "../func/upload.php",
<i> </i> method: "POST",
<i> </i> processData: false,
<i> </i> contentType: false,
<i> </i> data: fd,
<i> </i> enctype: 'multipart/form-data',
<i> </i> success: function (data) {
<i> </i> console.log('SUCCESS' + data);
<i> </i> },
<i> </i> error: function (err) {
<i> </i> }
<i> </i> });
}
Copy linkTweet thisAlerts:
@NogDogJul 03.2021 — Another consideration: for the move_uploaded_file() to work, the target directory needs to be writable by the web server user account that is actually executing the PHP code, so you may need to ensure the target directory is writable by that user (or all users or an applicable user group).

To help find out if that's the problem, you can turn on all error reporting to see what it says:
[code=php]
<?php
ini_set('display_errors', true); // set to false in production mode
error_reporting(E_ALL);

// rest of your code . . .
[/code]
Copy linkTweet thisAlerts:
@NitiphoneauthorJul 03.2021 — @NogDog#1633671 From I checked, seem the record sound is not record correctly

Every time I record always 1Kb size.

But I don't know why the sie is not change,

when I start and stop, I saw it's work but result It's not like what I think
//webkitURL is deprecated but nevertheless
URL = window.URL || window.webkitURL;

var gumStream; //stream from getUserMedia()
var rec; //Recorder.js object
var input; //MediaStreamAudioSourceNode we'll be recording

// shim for AudioContext when it's not avb.
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext //audio context to help us record


function startRecording() {

<i> </i>
<i> </i>var constraints = { audio: true, video:false }

<i> </i>navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
<i> </i> console.log("getUserMedia() success, stream created, initializing Recorder.js ...");

<i> </i> /*
<i> </i> create an audio context after getUserMedia is called
<i> </i> sampleRate might change after getUserMedia is called, like it does on macOS when recording through AirPods
<i> </i> the sampleRate defaults to the one set in your OS for your playback device

<i> </i> */
<i> </i> audioContext = new AudioContext();

<i> </i>

<i> </i> /* assign to gumStream for later use */
<i> </i> gumStream = stream;
<i> </i>
<i> </i> /* use the stream */
<i> </i> input = audioContext.createMediaStreamSource(stream);

<i> </i> /*
<i> </i> Create the Recorder object and configure to record mono sound (1 channel)
<i> </i> Recording 2 channels will double the file size
<i> </i> */
<i> </i> rec = new Recorder(input,{numChannels:1})

<i> </i> //start the recording process
<i> </i> rec.record();


<i> </i> //tell the recorder to stop the recording
<i> </i>rec.stop();
<i> </i>

<i> </i>}).catch(function(err) {
<i> </i> //enable the record button if getUserMedia() fails
<i> </i>
<i> </i>});
}


function stopRecording() {



<i> </i>//tell the recorder to stop the recording
<i> </i>rec.stop();

<i> </i>//stop microphone access
<i> </i>gumStream.getAudioTracks()[0].stop();
<i> </i>
<i> </i>//create the wav blob and pass it on to createDownloadLink
<i> </i>rec.exportWAV(createDownloadLink);
}

async function createDownloadLink(blob) {

var sizeInBytes = blob.size;
console.log('Size = ' + sizeInBytes);
//name of .wav file to use during upload and download (without extendion)
var filename = new Date().toISOString();
var url = URL.createObjectURL(blob);
<br/>
<i> </i>

<i> </i> var xhr=new XMLHttpRequest();
<i> </i> xhr.onload=function(e) {
<i> </i> if(this.readyState === 4) {
<i> </i> console.log("Server returned: ",e.target.responseText);
<i> </i> }
<i> </i> };
<i> </i> var fd=new FormData();
<i> </i> fd.append("audio_data",blob, filename);
<i> </i> xhr.open("POST","http://localhost/dlap/func/upload.php",true);
<i> </i> xhr.send(fd);


}
Copy linkTweet thisAlerts:
@SempervivumJul 03.2021 — Take a look at this piece of code:
``<i>
</i> //start the recording process
rec.record();


//tell the recorder to stop the recording
rec.stop();<i>
</i>
``

You start recording and immediately afterwards you stop it. The result will be a very small audio blob or file.
Copy linkTweet thisAlerts:
@NitiphoneauthorJul 05.2021 — @Sempervivum#1633673 Yes, you are right.

From this code. If I want to send (in document.ready) to the post also

How can I do? I add on createDownloadLink(blob,to_user_id) but it's error to_user_id: undefined
<i>
</i>async function createDownloadLink(blob,to_user_id) {


<i> </i>//name of .wav file to use during upload and download (without extendion)
<i> </i>var filename = new Date().toISOString();


<i> </i>
<i> </i> var fd=new FormData();
<i> </i>
<i> </i> fd.append('audio_data', blob,filename);
<i> </i> fd.append('to_user_id',to_user_id);
<i> </i>
<i> </i> $.ajax({

<i> </i> url: "../func/upload.php",
<i> </i> method: "POST",
<i> </i> processData: false,
<i> </i> contentType: false,
<i> </i>
<i> </i> data: fd,
<i> </i> enctype: 'multipart/form-data',
<i> </i> success: function (data) {
<i> </i> console.log('SUCCESS' + data);

<i> </i> },
<i> </i> error: function (err) {
<i> </i> }

<i> </i> });
Copy linkTweet thisAlerts:
@NitiphoneauthorJul 05.2021 — Now it's work. I have to combine javascript in the same file. seem I can't use variable in different file
Copy linkTweet thisAlerts:
@SempervivumJul 05.2021 — @Nitiphone#1633741
>seem I can't use variable in different file

You can, but they have to be global in this case.

As you wrote:
>If I want to send (in document.ready) to the post also

I suspect that the definition of the variable and referencing it were located in different blocks of:
``<i>
</i>$( document ).ready(function() {
// variables defined here are not global and it will not be possible
// to access them from outside
});<i>
</i>
``
×

Success!

Help @Nitiphone spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...