Just Jolly Functions
Functions: Creating a Voice Recording Widget with HTML, CSS, and JavaScript
You can create a Voice Recording Widget using HTML, CSS, and JavaScript. This widget will allow users to record their voice using their microphone, and it will display the recording duration as well as a button to start/stop the recording. The recorded audio can then be played back.
Tip: Learn how to Insert HTML Code into Your Post.
HTML, CSS, and JavaScript Combined Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voice Recording Widget</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
.recorder-container {
text-align: center;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
padding: 30px;
width: 300px;
}
.status {
font-size: 18px;
margin: 10px 0;
}
.timer {
font-size: 22px;
margin: 20px 0;
color: #333;
}
.record-btn {
padding: 15px 30px;
font-size: 16px;
color: white;
background-color: #007BFF;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s;
}
.record-btn:hover {
background-color: #0056b3;
}
.play-btn {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
color: white;
background-color: #28a745;
border: none;
border-radius: 8px;
cursor: pointer;
}
.play-btn:disabled {
background-color: #ccc;
}
</style>
</head>
<body>
<div class="recorder-container">
<h2>Voice Recorder</h2>
<p class="status">Click "Start Recording" to begin.</p>
<div class="timer" id="timer">00:00</div>
<button class="record-btn" id="recordBtn">Start Recording</button>
<button class="play-btn" id="playBtn" disabled>Play Recording</button>
<audio id="audioPlayer" controls style="display: none;"></audio>
</div>
<script>
let isRecording = false;
let recorder;
let audioChunks = [];
let timerInterval;
let timerSeconds = 0;
const statusEl = document.querySelector('.status');
const timerEl = document.getElementById('timer');
const recordBtn = document.getElementById('recordBtn');
const playBtn = document.getElementById('playBtn');
const audioPlayer = document.getElementById('audioPlayer');
// Request permission to access the microphone
async function initRecorder() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recorder = new MediaRecorder(stream);
recorder.ondataavailable = (event) => {
audioChunks.push(event.data);
};
recorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
audioPlayer.src = audioUrl;
playBtn.disabled = false; // Enable the play button
};
}
// Start recording
function startRecording() {
audioChunks = [];
recorder.start();
isRecording = true;
statusEl.textContent = "Recording in progress...";
recordBtn.textContent = "Stop Recording";
// Start the timer
timerInterval = setInterval(() => {
timerSeconds++;
let minutes = Math.floor(timerSeconds / 60);
let seconds = timerSeconds % 60;
timerEl.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}, 1000);
}
// Stop recording
function stopRecording() {
recorder.stop();
clearInterval(timerInterval);
isRecording = false;
statusEl.textContent = "Recording stopped.";
recordBtn.textContent = "Start Recording";
}
// Toggle recording on button click
recordBtn.addEventListener('click', () => {
if (isRecording) {
stopRecording();
} else {
startRecording();
}
});
// Play the recording
playBtn.addEventListener('click', () => {
audioPlayer.style.display = 'block';
audioPlayer.play();
});
// Initialize the recorder
initRecorder();
</script>
</body>
</html>
How the Code Works:
HTML Structure:
A simple layout with a container holding the status, timer, buttons for starting/stopping the recording, and a play button.
The audio element is used to play back the recorded audio after the recording is stopped.
CSS Styling:
The CSS provides a clean, modern design for the widget with a centered layout.
Button styles and hover effects are added for better interactivity.
The timer is displayed in the format MM:SS, showing the elapsed time while recording.
JavaScript Functionality:
The navigator.mediaDevices.getUserMedia API is used to request permission for accessing the microphone.
MediaRecorder is used to record the audio and store the audio chunks as they become available.
A timer starts when recording begins, updating every second and showing the elapsed time.
The "Start Recording" button toggles between starting and stopping the recording.
The "Play Recording" button is enabled once the recording stops, allowing the user to listen to the recorded audio.
How to Use:
Click "Start Recording" to begin recording your voice.
The timer will show the elapsed time during the recording.
Once you're done, click "Stop Recording" to stop the recording.
After the recording stops, click "Play Recording" to hear the audio you just recorded.
This is a basic voice recording widget and can be enhanced with features like uploading the audio, saving the recording to a server, or customizing the UI further.
Additional Customizations:
To enhance the voice recording widget further and provide more customization options, you can add various features that improve user experience, visual appeal, and functionality. Below are some suggested customizations to improve the widget, categorized into UI changes, functionality improvements, and feature additions.
1. UI Customizations:
Background Color & Styling:
Change the background color of the page or the recorder container.
Add gradients or more vibrant colors to the buttons and containers.
Button Animations:
Add animations or transitions for the buttons when clicked or hovered to make them feel more interactive.
Microphone Icon:
Display a microphone icon during recording for a clearer UI indication.
Loading Spinner:
Show a loading spinner when requesting microphone permissions or while recording.
Button Feedback:
Change the button text dynamically to provide clearer instructions (e.g., "Recording in Progress", "Stop Recording", etc.).
Timer Reset:
Reset the timer when the recording is stopped or replayed.
Custom CSS Example:
.recorder-container {
text-align: center;
background: linear-gradient(to right, #007BFF, #00bcd4);
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
padding: 35px;
width: 300px;
color: white;
}
.status {
font-size: 18px;
margin: 10px 0;
}
.timer {
font-size: 22px;
margin: 20px 0;
color: white;
}
.record-btn {
padding: 15px 30px;
font-size: 16px;
color: white;
background-color: #ff5722;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
}
.record-btn:hover {
background-color: #e64a19;
transform: scale(1.05);
}
.play-btn {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
color: white;
background-color: #4caf50;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
}
.play-btn:hover {
background-color: #388e3c;
transform: scale(1.05);
}
.play-btn:disabled {
background-color: #ccc;
cursor: not-allowed;
}
2. Functionality Enhancements:
Recording Timer Reset:
Ensure that the timer resets once the recording is finished or when the user clicks the "Start Recording" again.
Recording Quality Settings:
Allow users to select the quality of the recording (e.g., low, medium, high) by adjusting the MediaRecorder's options.
Download Recording:
Allow users to download the recording as a .wav or .mp3 file.
Custom JavaScript Example for Downloading:
function downloadRecording() {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
const a = document.createElement('a');
a.href = audioUrl;
a.download = 'recording.wav';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// Add download button event
const downloadBtn = document.createElement('button');
downloadBtn.textContent = "Download Recording";
downloadBtn.className = "play-btn";
document.querySelector('.recorder-container').appendChild(downloadBtn);
downloadBtn.addEventListener('click', downloadRecording);
Audio Visualization:
Add a waveform or volume visualization that shows the recording in real time.
Pause and Resume:
Allow the user to pause and resume the recording. This is useful in scenarios where they might need to take a break.
3. Feature Additions:
Recording Notifications:
Add visual or audio notifications to indicate when the recording starts and stops.
Voice-to-Text Integration:
Integrate speech-to-text functionality using the Web Speech API to convert the recorded speech into text, which can then be displayed in real time.
Example of Speech-to-Text:
const recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.interimResults = true;
recognition.onresult = function(event) {
let transcript = event.results[0][0].transcript;
statusEl.textContent = `Voice-to-Text: ${transcript}`;
};
function startVoiceRecognition() {
recognition.start();
}
Multiple Audio Formats:
Allow the user to choose between different audio formats for download (WAV, MP3, etc.). To convert to MP3, you'll need additional libraries like libmp3lame.js for encoding audio in the browser.
Save Recordings to Server (Advanced):
Implement functionality to send the recorded audio to a server for storage or further processing. This typically involves creating an endpoint in your server-side code (e.g., Node.js, Python) to receive and store the audio data.
Full Updated Example with Some Customizations:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voice Recording Widget</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
.recorder-container {
text-align: center;
background: linear-gradient(to right, #007BFF, #00bcd4);
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
padding: 35px;
width: 300px;
color: white;
}
.status {
font-size: 18px;
margin: 10px 0;
}
.timer {
font-size: 22px;
margin: 20px 0;
color: white;
}
.record-btn {
padding: 15px 30px;
font-size: 16px;
color: white;
background-color: #ff5722;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
}
.record-btn:hover {
background-color: #e64a19;
transform: scale(1.05);
}
.play-btn {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
color: white;
background-color: #4caf50;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
}
.play-btn:hover {
background-color: #388e3c;
transform: scale(1.05);
}
.play-btn:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.download-btn {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
color: white;
background-color: #007bff;
border: none;
border-radius: 8px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="recorder-container">
<h2>Voice Recorder</h2>
<p class="status">Click "Start Recording" to begin.</p>
<div class="timer" id="timer">00:00</div>
<button class="record-btn" id="recordBtn">Start Recording</button>
<button class="play-btn" id="playBtn" disabled>Play Recording</button>
<button class="download-btn" id="downloadBtn" disabled>Download Recording</button>
<audio id="audioPlayer" controls style="display: none;"></audio>
</div>
<script>
let isRecording = false;
let recorder;
let audioChunks = [];
let timerInterval;
let timerSeconds = 0;
const statusEl = document.querySelector('.status');
const timerEl = document.getElementById('timer');
const recordBtn = document.getElementById('recordBtn');
const playBtn = document.getElementById('playBtn');
const downloadBtn = document.getElementById('downloadBtn');
const audioPlayer = document.getElementById('audioPlayer');
async function initRecorder() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recorder = new MediaRecorder(stream);
recorder.ondataavailable = (event) => {
audioChunks.push(event.data);
};
recorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
audioPlayer.src = audioUrl;
playBtn.disabled = false;
downloadBtn.disabled = false;
};
}
function startRecording() {
audioChunks = [];
recorder.start();
isRecording = true;
statusEl.textContent = "Recording in progress...";
recordBtn.textContent = "Stop Recording";
timerInterval = setInterval(() => {
timerSeconds++;
let minutes = Math.floor(timerSeconds / 60);
let seconds = timerSeconds % 60;
timerEl.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}, 1000);
}
function stopRecording() {
recorder.stop();
clearInterval(timerInterval);
isRecording = false;
statusEl.textContent = "Recording stopped.";
recordBtn.textContent = "Start Recording";
}
recordBtn.addEventListener('click', () => {
if (isRecording) {
stopRecording();
} else {
startRecording();
}
});
playBtn.addEventListener('click', () => {
audioPlayer.style.display = 'block';
audioPlayer.play();
});
downloadBtn.addEventListener('click', () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
const a = document.createElement('a');
a.href = audioUrl;
a.download = 'recording.wav';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
initRecorder();
</script>
</body>
</html>
Key Customizations:
Recording Timer Reset: The timer resets and continues correctly.
Download Button: The user can download the recording after it stops.
Visual Enhancements: The UI is more vibrant with gradient backgrounds and interactive button animations.
These customizations improve the appearance, functionality, and usability of the voice recording widget.