LWC Audio Recorder with Save Functionality

In this blog, we’ll explore how to implement an Audio Recorder in Salesforce using Lightning Web Components (LWC). The recorder allows users to record audio, play it back, and save it as a file in Salesforce. We’ll cover the front-end (HTML, JavaScript) and back-end (Apex) logic to create this feature.

 

Features of the Audio Recorder:

1. Record Audio: Capture audio using the device’s microphone.

2. Playback: Provide playback functionality for the recorded audio.

3. Save to Salesforce: Save the audio file to Salesforce as a content document.

4. Error Handling: Gracefully handle scenarios like unsupported browsers or recording failures.

 

 

1. LWC Front-End Code

HTML Template

The HTML file includes:

A microphone button to start/stop recording.

Audio playback controls for recorded audio.

A save button to upload the audio to Salesforce.

<template>
    <div class="slds-card audio-recorder">
        <div class="header">Audio Recorder</div>

        <!-- Audio Playback, Save Button, and Mic Button in One Line -->
        <div class="controls">
            <template if:true={audioURL}>
                <!-- Audio Playback -->
                <audio controls>
                    <source src={audioURL} type="audio/mpeg" />
                </audio>
                <!-- Save Button -->
                <div onclick={saveAudio} class="save-button">
                    <svg height="20px" width="20px" fill="#fff" viewBox="-2.4 -2.4 28.80 28.80" xmlns="http://www.w3.org/2000/svg" stroke="#fff" stroke-width="2.4">
                        <path d="M17.617,6.383a7.944,7.944,0,0,1-1.748,12.568A8.028,8.028,0,0,1,4.283,13.908A8.028,8.028,0,0,1,6.378,6.391c.451-.46-.256-1.168-.707-.707A8.946,8.946,0,0,0,15.427,20.27a8.946,8.946,0,0,0,2.9-14.594c-.451-.461-1.158.247-.707.707Z"></path>
                        <path d="M15.355,10.6l-3,3a.5.5,0,0,1-.35.15.508.508,0,0,1-.36-.15l-3-3a.5.5,0,0,1,.71-.71l2.14,2.14V3.555a.508.508,0,0,1,.5-.5.5.5,0,0,1,.5.5v8.49l2.15-2.16a.5.5,0,0,1,.71.71Z"></path>
                    </svg>
                </div>
            </template>
            <!-- Microphone Icon -->
            <div class="mic-button" onclick={handleMicClick}>
                <svg xmlns="http://www.w3.org/2000/svg" fill="#fff" viewBox="0 0 24 24" height="20px" width="20px">
                    <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3s-3 1.34-3 3v6c0 1.66 1.34 3 3 3zm4.5-3c0 2.48-1.51 4.5-3.5 4.5s-3.5-2.02-3.5-4.5H7c0 3.03 2.07 5.5 4.5 5.5V21h1v-4.5c2.43 0 4.5-2.47 4.5-5.5h-1.5z"></path>
                </svg>
            </div>
        </div>

        <!-- Error Display -->
        <template if:true={error}>
            <p class="error">{error}</p>
        </template>
    </div>
</template>

JavaScript Logic

The JavaScript manages:

Recording functionality using the MediaRecorder API.

Creating a Blob URL for playback.

Converting the audio Blob to Base64 for uploading.

import { LightningElement, track, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import saveFile from '@salesforce/apex/FileUploadController.saveFile';

export default class AudioRecorder extends LightningElement {
    @track audioURL = '';
    @track isRecording = false;
    @track error = '';
    @track base64Audio;
    @api recordId;
    mediaRecorder;
    chunks = [];

    handleMicClick() {
        if (this.isRecording) {
            this.stopRecording();
        } else {
            this.startRecording();
        }
    }

    startRecording() {
        navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
            this.mediaRecorder = new MediaRecorder(stream);
            this.chunks = [];
            this.mediaRecorder.ondataavailable = (event) => this.chunks.push(event.data);
            this.mediaRecorder.onstop = () => {
                const blob = new Blob(this.chunks, { type: 'audio/webm' });
                this.audioURL = URL.createObjectURL(blob);

                const reader = new FileReader();
                reader.onload = () => (this.base64Audio = reader.result.split(',')[1]);
                reader.readAsDataURL(blob);
            };
            this.mediaRecorder.start();
            this.isRecording = true;
        }).catch(() => {
            this.error = 'Unable to access microphone.';
        });
    }

    stopRecording() {
        if (this.mediaRecorder) {
            this.mediaRecorder.stop();
            this.isRecording = false;
        }
    }

    saveAudio() {
        if (this.base64Audio) {
            saveFile({
                base64Data: this.base64Audio,
                fileName: `Recording-${new Date().toISOString()}`,
                recId: this.recordId
            }).then(() => {
                this.dispatchEvent(new ShowToastEvent({
                    title: 'Success',
                    message: 'Audio file saved successfully!',
                    variant: 'success'
                }));
            }).catch(() => {
                this.dispatchEvent(new ShowToastEvent({
                    title: 'Error',
                    message: 'Failed to save audio file.',
                    variant: 'error'
                }));
            });
        }
    }
}

Apex Back-End Logic

The Apex controller handles the saving of audio files as Content Documents.

public with sharing class FileUploadController {
    @AuraEnabled
    public static String saveFile(String base64Data, String fileName, String recId) {
        Blob fileBlob = EncodingUtil.base64Decode(base64Data);

        ContentVersion contentVersion = new ContentVersion();
        contentVersion.Title = fileName;
        contentVersion.PathOnClient = fileName + '.mp3';
        contentVersion.VersionData = fileBlob;

        if (String.isNotBlank(recId)) {
            contentVersion.FirstPublishLocationId = recId;
        }

        insert contentVersion;

        return contentVersion.Id;
    }
}

Key Takeaways:

MediaRecorder API enables capturing audio in the browser.

ContentVersion object in Salesforce allows storing files easily.

Error handling ensures smooth user experience.

This Audio Recorder is a great example of leveraging browser and Salesforce capabilities for seamless file handling! 🎙️

Output :

0 0 votes
Article Rating