Creating an advanced voice/meeting recorder with the functionalities you've described involves both frontend and backend development. Below is a comprehensive guide to building such a web application using Python with Flask for the backend, SQLite for the database, and HTML/CSS/JavaScript for the frontend.
Key Features to Implement:
-
Recording Tab:
- Start/Stop Recording
- Select Audio Source (Microphone, Desktop Audio, Both)
- Add/Edit Title
- Take Notes with Timestamps
- Mark Important Segments
- Add Custom Segments
-
Recordings Tab:
- List of Recorded Meetings
- Playback of Audio Files
- View Segments and Notes
- Display Recording Time Range
-
Backend:
- Flask Server to handle API requests
- Manage Recording Process
- Store Data in SQLite Database
Prerequisites:
- Python 3.x installed
pip for package management
- Basic knowledge of Flask, HTML, CSS, and JavaScript
Step 1: Setting Up the Project Structure
Create a project directory with the following structure:
advanced_recorder/
├── static/
│ ├── css/
│ │ └── styles.css
│ └── js/
│ └── scripts.js
├── templates/
│ ├── index.html
│ └── recordings.html
├── recordings/
├── app.py
├── models.py
├── requirements.txt
Step 2: Installing Required Packages
Create a requirements.txt file with the following content:
Flask
Flask-SQLAlchemy
pyaudio
wave
Install the packages using:
pip install -r requirements.txt
Step 3: Database Models
Create a models.py file to define database models using SQLAlchemy.
# models.py
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy()
class Recording(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(150), nullable=False)
filename = db.Column(db.String(150), nullable=False)
start_time = db.Column(db.DateTime, default=datetime.utcnow)
end_time = db.Column(db.DateTime)
notes = db.relationship('Note', backref='recording', lazy=True)
segments = db.relationship('Segment', backref='recording', lazy=True)
class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)
class Segment(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)
Step 4: Backend Implementation with Flask
Create an app.py file to handle routes and recording logic.
# app.py
import os
from flask import Flask, render_template, request, redirect, url_for, jsonify, send_from_directory
from models import db, Recording, Note, Segment
from datetime import datetime
import threading
import pyaudio
import wave
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///recordings.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
RECORDINGS_FOLDER = os.path.join(os.getcwd(), 'recordings')
if not os.path.exists(RECORDINGS_FOLDER):
os.makedirs(RECORDINGS_FOLDER)
# Global variables to manage recording state
is_recording = False
current_recording = None
audio_thread = None
def record_audio(filename, audio_source):
global is_recording
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2 if audio_source == 'both' else 1
RATE = 44100
p = pyaudio.PyAudio()
# Select input device based on audio_source
if audio_source == 'microphone':
input_device_index = None # Default microphone
elif audio_source == 'desktop':
# Desktop audio recording typically requires virtual audio devices
input_device_index = None # Placeholder
elif audio_source == 'both':
input_device_index = None # Placeholder for combined input
else:
input_device_index = None
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=input_device_index)
frames = []
while is_recording:
data = stream.read(CHUNK)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(os.path.join(RECORDINGS_FOLDER, filename), 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
@app.before_first_request
def create_tables():
db.create_all()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/recordings')
def recordings():
all_recordings = Recording.query.order_by(Recording.start_time.desc()).all()
return render_template('recordings.html', recordings=all_recordings)
@app.route('/start_record', methods=['POST'])
def start_record():
global is_recording, current_recording, audio_thread
data = request.json
title = data.get('title', 'Untitled')
audio_source = data.get('audio_source', 'both')
filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
new_recording = Recording(title=title, filename=filename, start_time=datetime.utcnow())
db.session.add(new_recording)
db.session.commit()
current_recording = new_recording
is_recording = True
audio_thread = threading.Thread(target=record_audio, args=(filename, audio_source))
audio_thread.start()
return jsonify({'status': 'Recording started', 'recording_id': new_recording.id})
@app.route('/stop_record', methods=['POST'])
def stop_record():
global is_recording, current_recording, audio_thread
if not is_recording:
return jsonify({'status': 'Not recording'}), 400
is_recording = False
audio_thread.join()
current_recording.end_time = datetime.utcnow()
db.session.commit()
return jsonify({'status': 'Recording stopped', 'recording_id': current_recording.id})
@app.route('/add_note', methods=['POST'])
def add_note():
data = request.json
recording_id = data.get('recording_id')
content = data.get('content')
new_note = Note(content=content, recording_id=recording_id, timestamp=datetime.utcnow())
db.session.add(new_note)
db.session.commit()
return jsonify({'status': 'Note added'})
@app.route('/add_segment', methods=['POST'])
def add_segment():
data = request.json
recording_id = data.get('recording_id')
name = data.get('name', 'Segment')
new_segment = Segment(name=name, recording_id=recording_id, timestamp=datetime.utcnow())
db.session.add(new_segment)
db.session.commit()
return jsonify({'status': 'Segment added'})
@app.route('/get_recordings', methods=['GET'])
def get_recordings():
all_recordings = Recording.query.order_by(Recording.start_time.desc()).all()
recordings_data = []
for rec in all_recordings:
recordings_data.append({
'id': rec.id,
'title': rec.title,
'filename': rec.filename,
'start_time': rec.start_time.strftime('%Y-%m-%d %H:%M:%S'),
'end_time': rec.end_time.strftime('%Y-%m-%d %H:%M:%S') if rec.end_time else '',
'notes': [{'content': note.content, 'timestamp': note.timestamp.strftime('%H:%M:%S')} for note in rec.notes],
'segments': [{'name': seg.name, 'timestamp': seg.timestamp.strftime('%H:%M:%S')} for seg in rec.segments]
})
return jsonify(recordings_data)
@app.route('/download/<filename>')
def download_file(filename):
return send_from_directory(RECORDINGS_FOLDER, filename)
if __name__ == '__main__':
app.run(debug=True)
Explanation of the Backend Code:
-
Database Setup:
- Models: Defines
Recording, Note, and Segment models.
- Database Initialization: Creates tables before the first request.
-
Recording Logic:
- record_audio Function: Handles audio recording using
pyaudio. It records based on the selected audio source and saves the file in the recordings directory.
- Start Record Endpoint (
/start_record): Starts the recording process in a separate thread and saves metadata to the database.
- Stop Record Endpoint (
/stop_record): Stops the recording, updates the end time in the database.
-
Additional Endpoints:
- Add Note (
/add_note): Adds a note to a specific recording.
- Add Segment (
/add_segment): Adds a segment marker to a recording.
- Get Recordings (
/get_recordings): Retrieves all recordings with their associated notes and segments.
- Download File (
/download/<filename>): Allows downloading of recorded audio files.
Step 5: Frontend Implementation
1. HTML Templates
templates/index.html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Advanced Meeting Recorder</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
</head>
<body>
<h1>Advanced Meeting Recorder</h1>
<div id="recording-tab">
<h2>Record a Meeting</h2>
<input type="text" id="title" placeholder="Enter meeting title">
<br><br>
<label for="audio_source">Audio Source:</label>
<select id="audio_source">
<option value="microphone">Microphone</option>
<option value="desktop">Desktop Audio</option>
<option value="both" selected>Both</option>
</select>
<br><br>
<button id="start-btn">Start Recording</button>
<button id="stop-btn" disabled>Stop Recording</button>
<br><br>
<div id="notes-section">
<h3>Notes</h3>
<textarea id="notes" placeholder="Type your notes here..."></textarea>
<button id="add-note-btn">Add Note</button>
</div>
<div id="segments-section">
<h3>Segments</h3>
<button id="important-segment-btn">Mark Important</button>
<input type="text" id="custom-segment-name" placeholder="Custom Segment Name">
<button id="add-segment-btn">Add Segment</button>
</div>
</div>
<br>
<div id="recordings-tab">
<a href="{{ url_for('recordings') }}">View Older Recordings</a>
</div>
<script src="{{ url_for('static', filename='js/scripts.js') }}"></script>
</body>
</html>
templates/recordings.html
<!-- templates/recordings.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Recorded Meetings</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
</head>
<body>
<h1>Recorded Meetings</h1>
<a href="{{ url_for('index') }}">Back to Recording</a>
<ul id="recordings-list">
{% for rec in recordings %}
<li>
<h3>{{ rec.title }}</h3>
<p>Recorded from {{ rec.start_time.strftime('%Y-%m-%d %H:%M:%S') }} to {{ rec.end_time.strftime('%Y-%m-%d %H:%M:%S') }}</p>
<audio controls>
<source src="{{ url_for('download_file', filename=rec.filename) }}" type="audio/wav">
Your browser does not support the audio element.
</audio>
<h4>Segments:</h4>
<ul>
{% for seg in rec.segments %}
<li>{{ seg.name }} at {{ seg.timestamp.strftime('%H:%M:%S') }}</li>
{% endfor %}
</ul>
<h4>Notes:</h4>
<ul>
{% for note in rec.notes %}
<li>[{{ note.timestamp.strftime('%H:%M:%S') }}] {{ note.content }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</body>
</html>
2. CSS Styles
static/css/styles.css
/* static/css/styles.css */
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1, h2, h3, h4 {
color: #333;
}
input, select, textarea, button {
padding: 10px;
margin: 5px 0;
width: 100%;
max-width: 400px;
}
button {
width: auto;
cursor: pointer;
}
#recordings-list li {
border: 1px solid #ccc;
padding: 15px;
margin-bottom: 10px;
}
3. JavaScript Functionality
static/js/scripts.js
// static/js/scripts.js
document.addEventListener('DOMContentLoaded', () => {
const startBtn = document.getElementById('start-btn');
const stopBtn = document.getElementById('stop-btn');
const addNoteBtn = document.getElementById('add-note-btn');
const addSegmentBtn = document.getElementById('add-segment-btn');
const importantSegmentBtn = document.getElementById('important-segment-btn');
let currentRecordingId = null;
startBtn.addEventListener('click', () => {
const title = document.getElementById('title').value;
const audio_source = document.getElementById('audio_source').value;
fetch('/start_record', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, audio_source })
})
.then(response => response.json())
.then(data => {
if (data.status === 'Recording started') {
currentRecordingId = data.recording_id;
startBtn.disabled = true;
stopBtn.disabled = false;
}
});
});
stopBtn.addEventListener('click', () => {
fetch('/stop_record', {
method: 'POST'
})
.then(response => response.json())
.then(data => {
if (data.status === 'Recording stopped') {
stopBtn.disabled = true;
startBtn.disabled = false;
currentRecordingId = data.recording_id;
alert('Recording saved successfully!');
}
});
});
addNoteBtn.addEventListener('click', () => {
const content = document.getElementById('notes').value;
if (!content) {
alert('Please enter a note.');
return;
}
if (!currentRecordingId) {
alert('No active recording.');
return;
}
fetch('/add_note', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ recording_id: currentRecordingId, content })
})
.then(response => response.json())
.then(data => {
if (data.status === 'Note added') {
document.getElementById('notes').value = '';
alert('Note added.');
}
});
});
addSegmentBtn.addEventListener('click', () => {
const name = document.getElementById('custom-segment-name').value || 'Custom Segment';
if (!currentRecordingId) {
alert('No active recording.');
return;
}
fetch('/add_segment', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ recording_id: currentRecordingId, name })
})
.then(response => response.json())
.then(data => {
if (data.status === 'Segment added') {
document.getElementById('custom-segment-name').value = '';
alert('Segment added.');
}
});
});
importantSegmentBtn.addEventListener('click', () => {
if (!currentRecordingId) {
alert('No active recording.');
return;
}
fetch('/add_segment', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ recording_id: currentRecordingId, name: 'Important Segment' })
})
.then(response => response.json())
.then(data => {
if (data.status === 'Segment added') {
alert('Important segment marked.');
}
});
});
});
Explanation of the Frontend Code:
-
index.html:
- Recording Interface: Allows the user to input a title, select the audio source, start/stop recording, add notes, and mark segments.
- Navigation: Link to view older recordings.
-
recordings.html:
- List of Recordings: Displays all recorded meetings with their details, audio playback, segments, and notes.
-
styles.css:
- Basic styling for a clean and user-friendly interface.
-
scripts.js:
- Handles the interaction with backend APIs:
- Start Recording: Sends a request to start recording with the provided title and audio source.
- Stop Recording: Sends a request to stop the recording.
- Add Note: Sends notes to the backend associated with the current recording.
- Add Segment: Sends segment information (either important or custom) to the backend.
Step 6: Running the Application
- Initialize the Database:
Ensure that the database tables are created by running the Flask application once.
python app.py
- Access the Application:
Open your browser and navigate to http://127.0.0.1:5000/ to access the recorder interface.
Additional Considerations:
-
Desktop Audio Recording:
- Note: Recording desktop audio (system audio) is more complex and often requires virtual audio devices or platform-specific solutions. The provided implementation uses a placeholder for desktop audio. You might need to integrate platform-specific tools or use browser-based recording for client-side desktop audio capture.
-
Handling Multiple Users:
- The current implementation assumes a single user. For multi-user support, you'd need to implement user authentication and associate recordings with specific users.
-
Security:
- Implement proper security measures to protect user data, especially if deploying the application publicly.
-
Error Handling:
- Add comprehensive error handling to manage exceptions and provide feedback to the user.
-
Enhancements:
- Implement real-time transcription, better UI/UX, segment navigation within playback, and more sophisticated audio source selection.
Conclusion
This guide provides a foundational structure for building an advanced voice/meeting recorder using Python Flask. Depending on your specific requirements and environment, you might need to adjust and enhance certain components, especially regarding audio source management and scalability. Remember to thoroughly test each feature and consider edge cases to ensure a robust application.