Super Forms
  • Drag & Drop Form Builder for WordPress
  • Quick start
    • Installation
    • Registration
    • Starting your 15 day trial
    • Purchasing a license
    • Activating a license
    • First time setup
    • Secure file uploads
    • Creating a form
    • Adding form elements
    • Editing elements
    • Publishing your form
    • FAQ
  • Account
    • Dashboard
      • Your Invoices
      • Billing details
      • Your Licenses
      • E-mail Notification
      • Password reset
      • Cancel subscription
  • Common problems
    • Common problems
      • Email delivery problems
        • Why is my form not sending emails?
        • Why are emails going into spam folder/inbox?
      • File upload problems
      • Session expired
      • reCaptcha Troubleshooting – Fix β€œNot Loading” & Verification Errors
  • Elements
    • Layout elements
      • Column/Grid
      • Multi-part / step
    • Form elements
      • Calculator
      • Signature
      • File upload
      • Datepicker
      • Variable field
      • Dropdown
      • Text field
      • Autosuggest
      • Keywords
      • Radio button
      • Keyword Field
      • Button
      • Audio Recording (microphone)
    • HTML elements
      • Heading
      • HTML (raw)
      • Image
      • TinyMCE
      • Divider
      • Spacer
      • PDF page break
      • Google map element WordPress form
  • Features
    • Basic
      • Confirmations emails
      • Save Form Progression (continue later)
      • Build In Translation System
      • Populate form
      • Popups
      • Import & Export
      • Hide form after submitting
      • Hide or lock out user from your forms
      • Validation
    • Advanced
      • WordPress form with Google sheets dropdown
      • Custom registration form for WordPress
      • Custom login form for WordPress
      • Custom lost password form for WordPress
      • Update current logged in user
      • Secrets
      • Prevent duplicate entries
      • Lock & hide form
      • Password protect
      • Conditional Logic
      • Tags system
      • Address lookup/auto complete
      • Analytics Tracking
      • Conversion Tracking
      • Distance & Duration Calculation
      • If statements
      • Foreach loops
      • E-mail Reminders
      • Variable Fields
      • Form templates - Include elements into other forms - WordPress
      • Transferring data from one form to another
    • Integrations
      • PDF Generator
      • Listings
      • WooCommerce Checkout
        • Fixed price checkout
        • Dynamic price checkout
        • Variable product checkout (variations)
        • Replacing the "Add to cart" on a product page with a form
        • Hiding product from shop and order via custom form
      • PayPal
      • MailChimp
      • Mailster
      • Zapier
      • Stripe (BETA)
      • WooCommerce Instant Order (in progress)
  • Tutorials
    • WordPress Form to Google Sheet Integration
    • GDPR Consent / Terms agreement
    • How to update the plugin
    • Sending emails to specific department for WordPress contact forms
  • Example Forms for WordPress
    • Booking 24 hours ahead of time
  • Developers
    • Code Examples
      • Lookup City by Zipcode for your WordPress form
      • Audio Recording Field
      • Custom API Phone Number Validation for Your WordPress Form
      • Updating WordPress user meta data after login
      • Automatically redirecting to next step after displaying text or a progress bar
      • Dropdown with groups (categories)
      • Prevent form submission based on entered field values
      • Track form submissions with GTM (Google Tag Manager)
      • Tracking Multi-part steps with Google Analytics
      • Tracking Multi-part steps with GTM data layer (dataLayer.push)
      • Track form submissions with third party
      • Compare input field value with database value
      • Insert form data into a custom database table
      • Delete database row after contact entry is deleted in WordPress
      • Limited date availability (slots) for your WordPress booking form
      • Send submitted form data to another site
      • Exclude empty fields from emails
      • Execute custom JS when a column becomes conditionally visible
      • Toolset Plugin: Update comma separated string to Array for meta data saved via Front-end Posting
      • Toolset Plugin: Update file ID to file URL for meta data saved via Front-end Posting
      • Delete uploaded files after email has been send
      • Increase Cookie lifetime for client data such as [Form Progression]
      • Altering cookie secure and httponly parameters
      • Define fake cronjob to clear old client data if cronjob is disabled on your server
      • Define page language attribute based on page ID or URL
      • Define custom headers when doing a POST request
      • Change checkbox/radio layout to vertical on mobile devices
      • Show remaining available form submission allowed
      • Global fields / elements
      • Trim values of fields
      • Re-sending E-mails after editing entries via Listings for WordPress
      • Combine multiple field values into one column on Contact Entries page
      • Altering the attachments for E-mails via PHP code for WordPress
      • Generate dynamic columns with dates based on user selected date from Datepicker element
    • Data storage
    • BETA version
  • Changelog
  • Support
Powered by GitBook
On this page
  1. Developers
  2. Code Examples

Audio Recording Field

WordPress form with microphone recording field. Allow your user to record audio and upload it as a audio file (webm). User can preview the recording and start a new recording if needed.

PreviousLookup City by Zipcode for your WordPress formNextCustom API Phone Number Validation for Your WordPress Form

Last updated 1 day ago

Live demo:

The JavaScript code will replace a regular file upload element with a "Start recording" button, which allows users to record voice via the browser by allowing to record their microphone.

For this to work, you will require custom JavaScript code (until we build a dedicated field or option to record audio). The JavaScript code will convert an existing File upload element into a "Record audio" element. It is required to name the file upload field audio_recording otherwise the JavaScript code won't function and nothing would happen.

To get the demo form up and running, simply copy paste the Form Elements code below under your [CODE] tab on the builder page. And make sure you place the JavaScript code on the same page where your form is located.

[
    {
        "tag": "text",
        "group": "form_elements",
        "data": {
            "name": "email",
            "email": "E-mail address:",
            "placeholder": "Your E-mail Address",
            "placeholderFilled": "E-mail Address",
            "type": "email",
            "validation": "email",
            "icon": "envelope;far"
        }
    },
    {
        "tag": "file",
        "group": "form_elements",
        "data": {
            "name": "audio_recording",
            "email": "File:",
            "extensions": "jpg|jpeg|png|gif|pdf|webm",
            "class": "f4d-audio-recording",
            "wrapper_class": "f4d-audio-recording-wrapper",
            "icon": "download"
        }
    }
]

JavaScript code (place this on the page where your form will be located.)

<script>Β 
(function () {
  function initAudioRecorder() {
    // Your audio logic here
    console.log("DOM ready – recorder initialized");
	  debugger;
	  const form = document.querySelector(".super-form");
	  if (!form) return;
	
		var hideFileUpload = document.querySelector('.f4d-audio-recording');
		if(hideFileUpload) hideFileUpload.style.display = 'none';
	  const recordBtn = document.createElement("button");
	  recordBtn.type = "button";
	  recordBtn.textContent = "πŸŽ™οΈ Start Recording";
	  recordBtn.style.margin = "10px 0";
	
	  const deleteBtn = document.createElement("button");
	  deleteBtn.type = "button";
	  deleteBtn.textContent = "❌ Delete Recording";
	  deleteBtn.style.display = "none";
	
	  //const audioPreview = document.createElement("audio");
	  //audioPreview.controls = true;
	  //audioPreview.style.display = "none";
	
	  // Find the Super Forms file input by name
	  const fileInput = form.querySelector('input[name="audio_recording"]').parentNode.querySelector('input[name="files[]"]');
	  let mediaRecorder;
	  let audioChunks = [];
	
	  recordBtn.addEventListener("click", async () => {
	    if (mediaRecorder && mediaRecorder.state === "recording") {
	      mediaRecorder.stop();
	      recordBtn.textContent = "πŸŽ™οΈ Start Recording";
	    } else {
	      try {
	        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
	        mediaRecorder = new MediaRecorder(stream);
	        audioChunks = [];
	
	        mediaRecorder.ondataavailable = (e) => {
	          if (e.data.size > 0) audioChunks.push(e.data);
	        };
				
			mediaRecorder.onstop = () => {
			  debugger;
			  const audioBlob = new Blob(audioChunks, { type: "audio/webm" });
			  const audioFile = new File([audioBlob], "recording.webm", { type: "audio/webm" });
			
			  const audioURL = URL.createObjectURL(audioBlob);
			
			  // STEP 1: Get form ID
				debugger;
				var fileInput = form.querySelector('input[name="audio_recording"]').parentNode.querySelector('input[name="files[]"]');
				const formEl = fileInput.closest(".super-form");
			  const formID = formEl.querySelector('input[name="hidden_form_id"]').value;
			  // STEP 2: Create Super Forms file entry
			  /*const fileData = {
			    name: audioFile.name,
			    size: audioFile.size,
			    type: audioFile.type,
			    file: audioFile,
			    src: audioURL
			  };*/
			
			  if (typeof SUPER.files === "undefined") SUPER.files = {};
			  if (typeof SUPER.files[formID] === "undefined") SUPER.files[formID] = {};
			  //SUPER.files[formID]["audio_recording"] = [fileData]; // name = your field name
			  SUPER.files[formID]["audio_recording"] = [audioFile];

			  // STEP 3: Update the preview (already done correctly)
			  const wrapper = fileInput.closest('.super-fileupload');
			  const fileListContainer = wrapper.parentNode.querySelector('.super-fileupload-files');
			  fileListContainer.innerHTML = "";
			
			  const fileDiv = document.createElement("div");
			  fileDiv.className = "super-uploaded";
			  fileDiv.setAttribute("data-name", "recording.webm");
			  fileDiv.setAttribute("title", "recording.webm");
			  fileDiv.setAttribute("data-type", "audio/webm");
			
			  const spanImg = document.createElement("span");
			  spanImg.className = "super-fileupload-image super-file-type-audio-webm";
			  spanImg.style.width = "180px";
			  spanImg.style.maxWidth = "180px";
			  const audioTag = document.createElement("audio");
			  audioTag.controls = true;
			  audioTag.src = audioURL;
			  spanImg.appendChild(audioTag);
			
			  const info = document.createElement("span");
			  info.className = "super-fileupload-info";
			
			  const fileName = document.createElement("span");
			  fileName.className = "super-fileupload-name";
			  fileName.textContent = "recording.webm";
			
			  const fileDelete = document.createElement("span");
			  fileDelete.className = "super-fileupload-delete";
			  fileDelete.style.cursor = "pointer";
			  fileDelete.title = "Delete";
			
			  fileDelete.addEventListener("click", () => {
			    fileListContainer.innerHTML = "";
			    fileInput.value = "";
			    deleteBtn.style.display = "none";
			    recordBtn.textContent = "πŸŽ™οΈ Start Recording";
			
			    // Clear from SUPER.files
			    if (SUPER.files?.[formID]?.["audio_recording"]) {
			      delete SUPER.files[formID]["audio_recording"];
			    }
			  });
			
			  info.appendChild(fileName);
			  info.appendChild(fileDelete);
			
			  fileDiv.appendChild(spanImg);
			  fileDiv.appendChild(info);
			
			  fileListContainer.appendChild(fileDiv);
			};


	
	        mediaRecorder.start();
	        recordBtn.textContent = "πŸ›‘ Stop Recording";
	      } catch (err) {
	        alert("Microphone access denied.");
	      }
	    }
	  });
	
	  deleteBtn.addEventListener("click", () => {
	    audioChunks = [];
	    //audioPreview.src = "";
	    //audioPreview.style.display = "none";
	    fileInput.value = ""; // Clear file input
	    deleteBtn.style.display = "none";
	    recordBtn.textContent = "πŸŽ™οΈ Start Recording";
	  });
	
	  // Insert into form (above the file field)
	  fileInput.parentElement.insertBefore(recordBtn, fileInput);
	  fileInput.parentElement.insertBefore(deleteBtn, fileInput);
	  //fileInput.parentElement.insertBefore(audioPreview, fileInput);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initAudioRecorder);
  } else {
    // DOM already ready
    initAudioRecorder();
  }
})();

</script>
https://super-forms.com/microphone-recording/