Become the Serverless DJ. How to course of audio utilizing AWS?
Intro
As software program builders, we work with several types of recordsdata. These are sometimes codecs like JSON, XML, or CSV. Data engineers, however, use extra specialised instruments corresponding to Parquet. Beyond textual content recordsdata, we additionally course of photographs – resizing them, adjusting colours, or altering shapes.
However, there may be one kind of medium that appears to be considerably neglected, regardless of surrounding us in every single place. After all, who would not take pleasure in listening to music to calm down or utilizing it as background sound whereas working?
But how will we work with audio recordsdata? How can we course of them within the AWS cloud? What features ought to we contemplate to make sure our structure is each scalable and cost-effective? I’ll reply these and lots of different questions on this article.
Full code will be discovered on my Github. I used Terraform to explain all AWS assets. This will enable you to arrange this challenge with out having to configure it manually. I made a decision to not use any architectures or design patterns as a result of I wished to maintain issues so simple as attainable. Feel free to increase it utilizing layers, interfaces, hexagonal structure and so forth.
Technologies used
In the world of contemporary cloud options, we’re continuously in search of methods to extend effectivity, scale back prices and eradicate pointless infrastructure. That is why selecting serverless expertise appeared like a pure step. Thanks to the mannequin during which I don’t have to fret about managing servers, I can deal with what’s most vital – processing audio in a quick, scalable and cost-optimized means. The following providers will assist me with this:
- Amazon S3 – The storage, the place we are going to save our recordsdata. It scales very properly and has excessive availability (99.999999999%). Mechanisms corresponding to Presigned URL or S3 Events can be an vital a part of our structure.
- AWS Lambda – This can be our fundamental working instrument that permits us to run our Node.js code. The fundamental benefit is that we solely pay for the time it takes to run, making it ideally suited for reacting to occasions. Cons? Maximum quarter-hour of runtime and 10GB of RAM.
- AWS API Gateway – This service enable us to show our Lambdas as REST API endpoints.
- DynamoDB – A NoSQL database that gives superb efficiency and scalability. To be capable of speak about its capabilities would require a separate (and never so brief) article. TLDR: DDB is for you if you happen to want an environment friendly and scalable database, and on the identical time you realize precisely what the question patterns can be.
-
Amazon SQS – A easy AWS queue that permits us to ship occasions in two modes:
- Normal – the place now we have nearly limitless scaling however duplicate messages are attainable.
- FIFO – the place duplicates are mechanically eliminated however with a restrict of 300 operations per second.
-
FFmpeg – This instrument permits us to customise and modify the audio file to go well with our wants. It is a CLI instrument designed for multimedia processing and consists of two subtools:
- FFmpeg – permits conversion to completely different codecs, trimming and merging recordsdata, altering the sampling price… and that’s simply the tip of the iceberg.
- FFprobe – permits us to investigate the file, together with checking measurement, format, and different attributes..
Well, a CLI instrument. Won’t that be an issue within the case of Lambda? After all, it’s a serverless resolution, which may be very high-level. Fortunately, there’s a solution to resolve this drawback, however extra on that later.
Architecture
When creating our resolution, we have to cowl three basic features:
- Upload – How can we effectively ship new recordsdata?
- Audio Processing – Similar to textual content recordsdata, audio recordsdata are available in a variety of codecs. Additionally, every file can have completely different sampling charges and channel configurations. Standardizing them will simplify additional processing.
- Metadata – It’s important to make sure that recordsdata will be simply searched and sorted later.
Here’s how the ultimate course of seems to be like.
Upload
Uploading a file looks like the least of your issues. After all, it is simply sending a file to our backend and throwing it into an S3 bucket? Right?
Well, probably not. Of course, it may be performed this fashion, however it will likely be inefficient. After all, in such an structure, our Lambda will work a bit like a shovel that has to maneuver a considerable amount of information and that’s its solely job. What if our consumer might add a file on to the Bucket?
Fortunately, AWS offers us with a Presigned URL mechanism that permits for direct add to the S3 Bucket. It’s quite simple:
- In step one, we ask the bucket to generate an URL that permits us to add file straight.
- After receiving the response from the URL, we do a redirect to it. We place our file within the physique of the brand new request.
Another issue to contemplate is the file measurement – bigger recordsdata might take longer to add and are extra inclined to community errors. The resolution is to make use of the Multipart Upload. It permits parallelization of requests and will increase resilience, for instance by enabling re-sending. For what recordsdata ought to it’s used?
- >100MB – it is best to think about using this mechanism.
- >5GB – AWS requires using Multipart Upload for recordsdata bigger than 5GB.
In this instance I’ll follow the PutObject for simplicity functions.
Audio Processing
With the uncooked audio file already saved, the subsequent step is to go it to Lambda to provoke processing. The easiest method is to make use of the S3 Events mechanism. It permits us to pay attention for the adjustments in directories and recordsdata. We specify the occasion kind, prefix, suffix, and the vacation spot service for the notification. From now on, every time a file is added that matches the foundations given above, an occasion is triggered that can begin our Lambda. Of course, it would not include the file itself – solely the metadata wanted to obtain it from our S3 bucket.
Alternatively, you should utilize EventBridge, which is a extra normal resolution that helps a a lot wider vary of providers and occasions.
As you possibly can see, this can be a quite simple structure and sadly not absolutely practical. There is one element that could be problematic and it’s "At least one supply" of S3 occasions. This signifies that duplicates might happen, which is able to trigger us to course of the identical file twice. The easiest method is to arrange a further SQS FIFO queue, which is able to mechanically reject duplicates and save us some computing assets. Note that it will solely work if we match into the SQS FIFO restrict (300 messages per second). To obtain larger throughput, we will use an answer like DynamoDB to trace whether or not a given occasion has already been processed.
Okay, however how ought to our precise audio processing appear like? How to make use of the FFmpeg in Node.js? There is 2 methods:
- You can straight name CLI instructions utilizing Node
child_process
import { exec } from 'child_process';
import { promisify } from 'util';
...
const execAsync = promisify(exec);
strive {
const { stderr } = await execAsync(`ffmpeg -i ${audioFilePath} -b:a ${bitrate} ${reworkedAudioPath}.${format}`);
if (stderr) {
console.warn('stderr:', stderr);
}
} catch (err) {
console.error('Error:', err.message);
if (err.stderr) {
console.error('stderr:', err.stderr);
}
}
- You also can use fluent-fmmpeg. It’s the NPM bundle that wraps ugly CLI instructions in a wonderful chain of features. I do know it is deprecated however it may nonetheless be helpful for many operations. Here’s how we use it:
await new Promise((resolve, reject) => {
ffmpeg(audioFilePath)
.toFormat(format) // Change format
.audioBitrate(bitrate) // Change bitrate
.save(reworkedAudioPath)
.on('finish', () => {
console.log('File has been reworked efficiently');
return resolve(reworkedAudioPath);
})
.on('error', (error: Error) => {
console.log('Failed to remodel audio file: ', error.message);
return reject(error);
});
});
Simple and straightforward to make use of. No matter what are the enter parameters, we nonetheless get the unified and predictable output. This helps us in additional processing. E.g. we no want to fret if given format is supported by the browser or not. We also can degrade the audio high quality to avoid wasting area on S3.
"But wait. You talked about that FFmpeg is a CLI instrument. Can we simply set up the library and count on it to work?" Well, sadly, it’s not that straightforward. We nonetheless must have FFmpeg put in on our system. But how can we do that? Do we have to put it in a ZIP with the Lambda code? This is the place Lambda Layers turns out to be useful. This mechanism permits us to pack our dependencies into archives, which may then be utilized in our features. We can embrace predefined dependencies, in addition to embrace exterior instruments. In our case, FFmpeg and FFprobe can be packaged on this means. We solely must zip the binaries, create the brand new layers and fix them to our Lambda operate. We additionally want to recollect to set the suitable FFMPEG_PATH and FFPROBE_PATH values utilizing Lambda setting variables.
From now on we will use FFmpeg CLI instructions.
Metadata
The final factor is the metadata wanted for later filtering and looking out of audio recordsdata, e.g. for frontend functions. Here, I’ll use DynamoDB as a database, which offers superb scalability and on demand fee (just for used assets). During the complete circulation, we are going to replace the present state of file processing, which seems to be as follows:
And that is the way it seems to be like within the code:
- Create new metadata report
export const createAudioMetadataFile = async (audioMetadata: AudioMetadata): Promise<void> => {
const documentClient = initDocumentClient();
const putCommand = new PutCommand({
TableName: course of.env.AUDIO_TABLE_NAME,
Item: audioMetadata,
});
await documentClient.ship(putCommand);
}
- Update report with new standing
const updateCommand = new UpdateCommand({
TableName: course of.env.AUDIO_TABLE_NAME,
Key: {
id: audioId,
},
UpdateExpression: 'SET #standing = :standing',
ExpressionAttributeNames: {
'#standing': 'standing',
},
ExpressionAttributeValues: {
':standing': 'UPLOADED' satisfies FileStanding,
},
});
Summary
The last structure seems to be as follows:
Let’s take a look at it!
First, we have to generate new Presigned URL. We get it within the response physique of our POST /api/recordsdata endpoint.
Then we use it within the PUT methodology. We also can leverage HTTP 301 code to mechanically redirect after profitable response. This begins the entire processing circulation. We can get up to date metadata with GET /api/recordsdata endpoint that lists all of the uploaded recordsdata.
As you possibly can see, even such a easy job ought to be properly deliberate with consideration to particulars corresponding to scaling, duplicates or low working price of our resolution. Of course, such structure is barely a base for extra advanced enterprise instances, so I encourage you to experiment.
Links
HI-FI News
by way of DEV Community https://dev.to
June 2, 2025 at 07:17PM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT












