How to Upload a .wav File on S3
Record audio and upload it to AWS S3
In this post, I'm going to share how I uploaded recorded audio to AWS S3 when I was working on a website(using MERN). This whole process tin be broken downwardly into ii simple steps:
- Recording of audio.
- Uploading the file to S3 using AWS-SDK
- Recording of sound using mic-recorder-to-mp3 npm
Set-Up:
Create a react app and remove the files which are not required
npx create-react-app audiorecord
Start with the installation of the required package
npm install --salve mic-recorder-to-mp3
mic-recorder-to-mp3 is an npm package that records the audio and returns buffer and blob.
Create an example:
const audioRecorder = new MicRecorder({ bitRate: 128 });
Audio Recording:
First, we demand to go admission to tape the sound which can be done by using navigator.getUserMedia()
navigator.getUserMedia({ audio: truthful ,video:false}, .and then() => { console.log('Permission Granted'); this.setState({ isblocked: false });
}, .catch() => { console.log('Permission Denied'); this.setState({ isblocked: truthful }) }, );
Add push with event handler onClick as follows:
<push onClick={this.beginning} disabled={this.land.isrecording} blazon="button">Start</push button> <push onClick={this.cease} blazon="push">Stop</button>
this.start and this.stop are the functions called when "Start" and "Stop" buttons are clicked. In start function, we check whether the access for audio is given and showtime recording. In stop function, we get buffer and blob as a response which is converted to file of wav format with name equally time in the number of milliseconds since midnight January 1, 1970, UTC to continue information technology random.
kickoff = () => { if(this.state.isblocked){ console.log('permission Denied'); }else{ audioRecorder.start() .then(()=>{ this.setState({ isrecording:true }); }).catch((eastward)=> console.log(e)); } }; cease = () => { audioRecorder.stop() .getMp3() .then(([buffer,hulk])=>{ const blobUrl = URL.createObjectURL(hulk) this.setState({blobUrl,isrecording:fake}); var d = new Engagement(); var file = new File([blob],d.valueOf(),{ type:"sound/wav" }) console.log(file); this.handleaudiofile(file); }).catch((e)=>panel.log('We could not remember your message')); };
After the file is created we pass it to this.handleaudiofile which handles uploading of the file to AWS S3
two. Upload the file to AWS S3
Since I was new to AWS, I searched how to upload a file to AWS S3 and came across this post past Mohamed Khelif on Medium which worked perfectly.
Since I referred to this blog I would like to explain it the way I understood it and it worked for me. So here it goes:
What is AWS Simple Storage Service or in brusque AWS S3?
It'south a service offered by Amazon Web Services that provides object storage through a web service interface. Information technology is similar to locker services provided past banks.
Then if y'all are going to use banking company lockers service, You accept to first, open an account in the respective bank. Whenever you lot go either to add or remove items from the locker you use the central to access the locker.
Here S3 service is analogous to the locker services; Bucket to business relationship; Pre-Signed URL to the cardinal.
Frontend :
We pass the sound file to handleaudiofile() from which nosotros collect the file name and type and pass information technology to role in the backend sign_s3 using Axios. In AWS s3 each object has object URL of the format-
https://{Saucepan NAME}.s3.{REGION}.amazonaws.com/{FILENAME}.
therefore we demand to pass the file as the parameter. In return, we get a pre-signed URL.
As mentioned we use a pre-signed URL to upload the audio which is passed to sign_s3 role along with file and header which uploads the audio to s3 saucepan using a pre-signed URL which expires in the specified time and cannot be used to further upload the audio.
handleaudiofile(ev){ permit file = ev; permit fileName = ev.name; let fileType = ev.type; axios.post("http://localhost:5000/sign_s3",{ fileName : fileName, //parameter 1 fileType : fileType //parameter 2 }) .and so(response => { var returnData = response.information.information.returnData; var signedRequest = returnData.signedRequest; var url = returnData.url; var options = { headers: { 'Content-Type': fileType, } }; axios.put(signedRequest,file,options) .then(issue => { this.setState({sound: url, },()=> console.log(this.country.audio)) alert("audio uploaded")}) .catch(error => { alert("ERROR " + JSON.stringify(error)); }) }) .catch(fault => { alarm(JSON.stringify(fault)); }) }
Backend:
After getting access key Id, copy it to .env file and add information technology to the listing of .gitignore file so that your Id and key are not available to anyone else.
Add all the details to s3Params object and we use it to get our signed URL using getSignedUrl() present in aws-sdk. So nosotros create an example of aws.S3() and call getSignedUrl().
var aws = crave('aws-sdk'); crave('dotenv').config(); // Configure dotenv to load in the .env file // Configure aws with your accessKeyId and your secretAccessKey aws.config.update({ region: 'us-due east-2', // Put your aws region here accessKeyId: process.env.AWSAccessKeyId, secretAccessKey: process.env.AWSSecretKey }) const S3_BUCKET = process.env.Bucket // Now lets export this office then we can call it from somewhere else exports.sign_s3 = (req,res) => { const s3 = new aws.S3(); // Create a new instance of S3 const fileName = req.torso.fileName; const fileType = req.body.fileType; // Fix the payload of what we are sending to the S3 api const s3Params = { Bucket: S3_BUCKET, Cardinal: fileName, Expires: 3000, ContentType: fileType, ACL: 'public-read' }; // Brand a request to the S3 API to become a signed URL which nosotros tin can apply to upload our file s3.getSignedUrl('putObject', s3Params, (err, data) => { if(err){ panel.log(err); res.json({error: err}) } // Data payload of what we are sending back, the url of the signedRequest and a URL where we tin can access the content after its saved. const returnData = { signedRequest: data, url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}` }; res.json({data:{returnData}}); }); }
Output
Conclusion:
Yous tin can discover the link for Git Repo for this project here
Cheers for reading, delight share your feedback in the comment section. If you found this mail service helpful feel free to share information technology.
phillipsnestandmand.blogspot.com
Source: https://medium.com/@sanjana01999/record-audio-and-upload-it-to-aws-s3-409f5e620805
0 Response to "How to Upload a .wav File on S3"
ارسال یک نظر