បាទ/ចាស! ខ្ញុំនឹងបង្កើត Web App កាត់តវីដេអូ ដោយ JavaScript + FFmpeg.wasm ដែលដំណើរការលើ Browser ទាំងស្រុង ។
---
🎯 លក្ខណៈពិសេស
លក្ខណៈ ស្ថានភាព
✅ ដំណើរការលើ Browser ✅
✅ មិនត្រូវការដំឡើង ✅
✅ Upload វីដេអូ ✅
✅ កាត់វីដេអូ (Trim) ✅
✅ បន្ថែមអក្សរខ្មែរ ✅
✅ បន្ថែម Watermark ✅
✅ Export MP4 ✅
✅ Khmer Unicode ✅
---
📄 កូដពេញលេច — index.html
```html
<!DOCTYPE html>
<html lang="km">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>កម្មវិធីកាត់តវីដេអូ - Khmer Video Editor</title>
<!-- Khmer Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Battambang:wght@400;700&family=Moul&family=Kantumruy+Pro:wght@400;600;700&display=swap" rel="stylesheet"/>
<!-- FFmpeg.wasm -->
<script src="https://unpkg.com/@ffmpeg/ffmpeg@0.12.10/dist/umd/ffmpeg.js"></script>
<script src="https://unpkg.com/@ffmpeg/util@0.12.1/dist/umd/index.js"></script>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body {
font-family: 'Kantumruy Pro', 'Battambang', sans-serif;
background: linear-gradient(135deg, #1e3a8a 0%, #0f172a 100%);
min-height: 100vh;
padding: 20px;
color: #fff;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
text-align: center;
margin-bottom: 30px;
}
.header h1 {
font-family: 'Moul', serif;
font-size: 32px;
color: #ffe600;
text-shadow: 2px 2px 6px rgba(0,0,0,0.4);
margin-bottom: 8px;
}
.header p { color: #cbd5e1; font-size: 15px; }
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 20px;
}
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
.panel {
background: rgba(255,255,255,0.05);
backdrop-filter: blur(10px);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 12px;
padding: 20px;
box-shadow: 0 8px 30px rgba(0,0,0,0.2);
}
.panel h2 {
font-size: 18px;
margin-bottom: 15px;
color: #ffe600;
border-bottom: 2px solid #2563eb;
padding-bottom: 8px;
font-family: 'Moul', serif;
}
.upload-area {
border: 2px dashed #2563eb;
border-radius: 10px;
padding: 30px;
text-align: center;
cursor: pointer;
transition: 0.3s;
background: rgba(37,99,235,0.1);
}
.upload-area:hover {
border-color: #ffe600;
background: rgba(255,230,0,0.1);
}
.upload-area input { display: none; }
.upload-area i {
font-size: 48px;
color: #2563eb;
margin-bottom: 10px;
display: block;
}
.preview-video {
width: 100%;
max-height: 300px;
border-radius: 8px;
background: #000;
margin-top: 15px;
}
.field {
margin-bottom: 15px;
}
.field label {
display: block;
font-size: 13px;
margin-bottom: 6px;
color: #cbd5e1;
font-weight: 600;
}
.field input[type="text"],
.field input[type="number"],
.field select,
.field textarea {
width: 100%;
padding: 10px 12px;
border: 1px solid rgba(255,255,255,0.2);
background: rgba(0,0,0,0.3);
color: #fff;
border-radius: 6px;
font-family: inherit;
font-size: 14px;
outline: none;
transition: 0.3s;
}
.field input:focus,
.field select:focus,
.field textarea:focus {
border-color: #ffe600;
background: rgba(0,0,0,0.5);
}
.field textarea { resize: vertical; min-height: 60px; }
.row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
/* Khmer Font Preview */
.khmer-preview {
background: rgba(0,0,0,0.4);
border-radius: 8px;
padding: 15px;
margin-bottom: 15px;
text-align: center;
min-height: 80px;
display: flex;
align-items: center;
justify-content: center;
}
.khmer-text-preview {
font-family: 'Moul', 'Battambang', serif;
font-size: 24px;
color: #ffe600;
text-shadow: 2px 2px 4px rgba(0,0,0,0.8);
word-break: break-word;
line-height: 1.5;
}
.btn {
width: 100%;
padding: 14px;
border: none;
border-radius: 8px;
font-family: 'Moul', 'Kantumruy Pro', serif;
font-size: 15px;
font-weight: 700;
cursor: pointer;
transition: 0.3s;
margin-bottom: 10px;
}
.btn-primary {
background: linear-gradient(135deg, #2563eb, #1e40af);
color: #fff;
box-shadow: 0 4px 15px rgba(37,99,235,0.4);
}
.btn-primary:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(37,99,235,0.6);
}
.btn-success {
background: linear-gradient(135deg, #10b981, #059669);
color: #fff;
box-shadow: 0 4px 15px rgba(16,185,129,0.4);
}
.btn-success:hover:not(:disabled) {
transform: translateY(-2px);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.progress-container {
margin-top: 15px;
display: none;
}
.progress-container.active { display: block; }
.progress-bar {
width: 100%;
height: 8px;
background: rgba(255,255,255,0.1);
border-radius: 4px;
overflow: hidden;
margin-bottom: 8px;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #2563eb, #ffe600);
width: 0%;
transition: width 0.3s;
border-radius: 4px;
}
.progress-text {
font-size: 12px;
color: #cbd5e1;
text-align: center;
}
.log {
background: rgba(0,0,0,0.5);
border-radius: 6px;
padding: 12px;
font-family: 'Courier New', monospace;
font-size: 11px;
color: #10b981;
max-height: 150px;
overflow-y: auto;
margin-top: 15px;
line-height: 1.6;
}
.log:empty { display: none; }
.warning {
background: rgba(245,158,11,0.15);
border: 1px solid #f59e0b;
color: #fbbf24;
padding: 10px 15px;
border-radius: 8px;
font-size: 12px;
margin-bottom: 15px;
line-height: 1.6;
}
.download-area {
display: none;
margin-top: 15px;
padding: 15px;
background: rgba(16,185,129,0.15);
border: 2px solid #10b981;
border-radius: 8px;
text-align: center;
}
.download-area.active { display: block; }
.download-area a {
display: inline-block;
background: #10b981;
color: #fff;
padding: 12px 30px;
border-radius: 8px;
text-decoration: none;
font-weight: 700;
font-family: 'Moul', serif;
transition: 0.3s;
}
.download-area a:hover {
background: #059669;
transform: translateY(-2px);
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🎬 កម្មវិធីកាត់តវីដេអូ</h1>
<p>កាត់តវីដេអូ បន្ថែមអក្សរខ្មែរ និង Export ដោយស្វ័យប្រវត្តិ</p>
</div>
<!-- Warning -->
<div class="warning">
⚠️ <strong>សំខាន់</strong>៖ App នេះត្រូវការដំណើរការលើ <strong>HTTPS</strong> ឬ <strong>localhost</strong> ។
បើបើកដោយផ្ទាល់ (file://) នឹងមិនដំណើរការទេ ។
</div>
<div class="grid">
<!-- LEFT: Upload & Preview -->
<div class="panel">
<h2>📁 ជ្រើសវីដេអូ</h2>
<div class="upload-area" onclick="document.getElementById('videoInput').click()">
<i>📤</i>
<div>ចុចទីនេះដើម្បីជ្រើសវីដេអូ</div>
<div style="font-size:12px;color:#94a3b8;margin-top:5px;">MP4, AVI, MOV, MKV</div>
<input type="file" id="videoInput" accept="video/*"/>
</div>
<video class="preview-video" id="previewVideo" controls style="display:none;"></video>
<div id="videoInfo" style="display:none;margin-top:15px;padding:12px;background:rgba(0,0,0,0.3);border-radius:8px;font-size:13px;">
<div>📊 <strong>File:</strong> <span id="fileName"></span></div>
<div>⏱️ <strong>Duration:</strong> <span id="fileDuration"></span></div>
<div>📦 <strong>Size:</strong> <span id="fileSize"></span></div>
</div>
</div>
<!-- RIGHT: Editor Settings -->
<div class="panel">
<h2>⚙️ ការកំណត់</h2>
<!-- Trim -->
<div class="field">
<label>⏰ ពេលចាប់ផ្តើម (វិនាទី)</label>
<input type="number" id="startTime" value="0" min="0" step="0.1"/>
</div>
<div class="field">
<label>⏰ ពេលបញ្ចប់ (វិនាទី)</label>
<input type="number" id="endTime" value="30" min="0" step="0.1"/>
</div>
<!-- Khmer Text -->
<div class="field">
<label>📝 អក្សរខ្មែរ (Text Overlay)</label>
<textarea id="khmerText" placeholder="វាយអក្សរខ្មែរនៅទីនេះ...">សូមស្វាគមន៍</textarea>
</div>
<div class="field">
<label>🔤 ទំហំអក្សរ</label>
<input type="number" id="fontSize" value="48" min="12" max="120"/>
</div>
<div class="row">
<div class="field">
<label>🎨 ពណ៌អក្សរ</label>
<input type="color" id="textColor" value="#ffe600" style="height:40px;padding:2px;"/>
</div>
<div class="field">
<label>📍 ទីតាំង</label>
<select id="textPosition">
<option value="top">ខាងលើ</option>
<option value="middle">កណ្តាល</option>
<option value="bottom" selected>ខាងក្រោម</option>
</select>
</div>
</div>
<!-- Preview -->
<div class="field">
<label>👁️ មើលជាមុន</label>
<div class="khmer-preview">
<div class="khmer-text-preview" id="textPreview">សូមស្វាគមន៍</div>
</div>
</div>
<!-- Actions -->
<button class="btn btn-primary" id="btnProcess" disabled>
🎬 ចាប់ផ្តើមកាត់ត
</button>
<!-- Progress -->
<div class="progress-container" id="progressContainer">
<div class="progress-bar">
<div class="progress-fill" id="progressFill"></div>
</div>
<div class="progress-text" id="progressText">កំពុងដំណើរការ...</div>
</div>
<!-- Log -->
<div class="log" id="log"></div>
<!-- Download -->
<div class="download-area" id="downloadArea">
<div style="margin-bottom:10px;">✅ កាត់តរួចរាល់!</div>
<a id="downloadLink" download="output.mp4">⬇️ ទាញយកវីដេអូ</a>
</div>
</div>
</div>
</div>
<script>
// ============================================================
// KHmer Video Editor — FFmpeg.wasm
// ============================================================
const { FFmpeg } = FFmpegWASM;
const { fetchFile, toBlobURL } = FFmpegUtil;
let ffmpeg = null;
let uploadedFile = null;
let videoDuration = 0;
const videoInput = document.getElementById('videoInput');
const previewVideo = document.getElementById('previewVideo');
const btnProcess = document.getElementById('btnProcess');
const progressContainer = document.getElementById('progressContainer');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
const logEl = document.getElementById('log');
const downloadArea = document.getElementById('downloadArea');
const downloadLink = document.getElementById('downloadLink');
// ============================================================
// Log Function
// ============================================================
function log(msg) {
const time = new Date().toLocaleTimeString();
logEl.textContent += `[${time}] ${msg}\n`;
logEl.scrollTop = logEl.scrollHeight;
console.log(msg);
}
// ============================================================
// Load FFmpeg
// ============================================================
async function loadFFmpeg() {
if (ffmpeg) return ffmpeg;
log('📥 កំពុងទាញ FFmpeg...');
ffmpeg = new FFmpeg();
ffmpeg.on('log', ({ message }) => {
console.log('[FFmpeg]', message);
});
ffmpeg.on('progress', ({ progress, time }) => {
const percent = Math.round(progress * 100);
progressFill.style.width = percent + '%';
progressText.textContent = `កំពុងដំណើរការ... ${percent}%`;
});
const baseURL = 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/umd';
await ffmpeg.load({
coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'),
wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm'),
});
log('✅ FFmpeg រួចរាល់');
return ffmpeg;
}
// ============================================================
// Handle Video Upload
// ============================================================
videoInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
uploadedFile = file;
// Show preview
previewVideo.src = URL.createObjectURL(file);
previewVideo.style.display = 'block';
// Show info
document.getElementById('fileName').textContent = file.name;
document.getElementById('fileSize').textContent = (file.size / 1024 / 1024).toFixed(2) + ' MB';
// Get duration
previewVideo.onloadedmetadata = () => {
videoDuration = previewVideo.duration;
document.getElementById('fileDuration').textContent = videoDuration.toFixed(1) + ' វិនាទី';
document.getElementById('endTime').value = Math.min(30, videoDuration).toFixed(1);
document.getElementById('endTime').max = videoDuration;
document.getElementById('startTime').max = videoDuration;
document.getElementById('videoInfo').style.display = 'block';
};
btnProcess.disabled = false;
log(`✅ បាន Upload: ${file.name}`);
});
// ============================================================
// Khmer Text Preview
// ============================================================
const khmerText = document.getElementById('khmerText');
const textPreview = document.getElementById('textPreview');
const fontSize = document.getElementById('fontSize');
const textColor = document.getElementById('textColor');
function updatePreview() {
textPreview.textContent = khmerText.value || 'សូមស្វាគមន៍';
textPreview.style.fontSize = fontSize.value + 'px';
textPreview.style.color = textColor.value;
}
khmerText.addEventListener('input', updatePreview);
fontSize.addEventListener('input', updatePreview);
textColor.addEventListener('input', updatePreview);
// ============================================================
// Process Video
// ============================================================
btnProcess.addEventListener('click', async () => {
if (!uploadedFile) {
alert('សូម Upload វីដេអូជាមុន!');
return;
}
btnProcess.disabled = true;
downloadArea.classList.remove('active');
progressContainer.classList.add('active');
progressFill.style.width = '0%';
progressText.textContent = 'កំពុងចាប់ផ្តើម...';
try {
// Load FFmpeg
const ff = await loadFFmpeg();
// Get settings
const start = parseFloat(document.getElementById('startTime').value) || 0;
const end = parseFloat(document.getElementById('endTime').value) || videoDuration;
const duration = end - start;
const text = khmerText.value.trim();
const size = parseInt(fontSize.value);
const color = textColor.value.replace('#', '0x');
const position = document.getElementById('textPosition').value;
// Position Y
let yPos = 'h-th-40'; // bottom
if (position === 'top') yPos = '40';
if (position === 'middle') yPos = '(h-th)/2';
log('🎬 ចាប់ផ្តើម Process...');
log(`⏰ Trim: ${start}s → ${end}s (${duration.toFixed(1)}s)`);
log(`📝 Text: "${text}"`);
// Write input file
log('📤 កំពុង Upload ទៅ FFmpeg...');
const inputName = 'input.' + uploadedFile.name.split('.').pop();
await ff.writeFile(inputName, await fetchFile(uploadedFile));
// Build FFmpeg command
const outputName = 'output.mp4';
// Escape text for FFmpeg drawtext filter
// FFmpeg requires escaping special characters
const escapedText = text
.replace(/\\/g, '\\\\')
.replace(/:/g, '\\:')
.replace(/'/g, "\\'")
.replace(/%/g, '\\%');
let args;
if (text) {
// With text overlay
// Use Khmer-compatible font
// Note: FFmpeg.wasm has limited Khmer font support
// We'll use drawtext with basic support
const fontFile = 'font.ttf';
// Download Khmer font
log('📥 កំពុងទាញ Khmer Font...');
try {
const fontUrl = 'https://github.com/google/fonts/raw/main/ofl/notosanskhmer/NotoSansKhmer%5Bwdth%2Cwght%5D.ttf';
const fontData = await fetch(fontUrl);
const fontBuffer = await fontData.arrayBuffer();
await ff.writeFile(fontFile, new Uint8Array(fontBuffer));
log('✅ Font រួចរាល់');
} catch(e) {
log('⚠️ ទាញ Font មិនបាន ប្រើ Default');
}
args = [
'-ss', start.toString(),
'-i', inputName,
'-t', duration.toString(),
'-vf', `drawtext=fontfile=${fontFile}:text='${escapedText}':fontcolor=${color}:fontsize=${size}:x=(w-text_w)/2:y=${yPos}:box=1:boxcolor=black@0.5:boxborderw=10`,
'-c:v', 'libx264',
'-preset', 'ultrafast',
'-crf', '23',
'-c:a', 'aac',
outputName
];
} else {
// Without text overlay
args = [
'-ss', start.toString(),
'-i', inputName,
'-t', duration.toString(),
'-c:v', 'libx264',
'-preset', 'ultrafast',
'-crf', '23',
'-c:a', 'aac',
outputName
];
}
log('🔧 Command: ffmpeg ' + args.join(' '));
log('⏳ កំពុងដំណើរការ...');
// Execute
await ff.exec(args);
log('✅ Process រួចរាល់');
// Read output
const data = await ff.readFile(outputName);
const blob = new Blob([data.buffer], { type: 'video/mp4' });
const url = URL.createObjectURL(blob);
// Show download
downloadLink.href = url;
downloadArea.classList.add('active');
// Cleanup
await ff.deleteFile(inputName);
await ff.deleteFile(outputName);
log('🎉 រួចរាល់! ចុចទាញយក');
} catch (error) {
log('❌ Error: ' + error.message);
console.error(error);
alert('មានបញ្ហា: ' + error.message);
} finally {
btnProcess.disabled = false;
progressText.textContent = 'រួចរាល់';
}
});
// ============================================================
// Check Browser Support
// ============================================================
if (typeof SharedArrayBuffer === 'undefined') {
log('⚠️ Browser មិនគាំទ្រ SharedArrayBuffer');
log('⚠️ ត្រូវការ HTTPS ឬ localhost');
document.querySelector('.warning').innerHTML =
'❌ <strong>Browser មិនគាំទ្រ!</strong> ត្រូវការ Chrome/Edge ថ្មី និង HTTPS ។';
}
updatePreview();
log('✅ App រួចរាល់');
</script>
</body>
</html>
```
---
📥 របៀបដំណើរការ
⚠️ សំខាន់ — ត្រូវការ HTTPS ឬ localhost
FFmpeg.wasm ត្រូវការ SharedArrayBuffer ដែលត្រូវការ COOP/COEP Headers ។
🔧 វិធីទី ១៖ ប្រើ VS Code + Live Server
1. ដំឡើង VS Code
2. ដំឡើង Extension Live Server
3. Save កូដជា index.html
4. Right-click → Open with Live Server
🔧 វិធីទី ២៖ ប្រើ Python Server
```bash
# Python 3
python -m http.server 8000
```
បន្ទាប់មកបើក ៖ http://localhost:8000
🔧 វិធីទី ៣៖ ប្រើ Node.js
```bash
npx serve
```
🔧 វិធីទី ៤៖ Deploy លើ Netlify/Vercel
1. Upload index.html ទៅ Netlify
2. វានឹងផ្តល់ HTTPS ស្វ័យប្រវត្តិ
---
🎯 របៀបប្រើ
1. ចុច Upload → ជ្រើសវីដេអូ
2. កំណត់ពេល ចាប់ផ្តើម និងបញ្ចប់
3. វាយអក្សរខ្មែរ ក្នុង Text Box
4. ជ្រើសពណ៌ ទំហំ ទីតាំង
5. ចុច "ចាប់ផ្តើមកាត់ត"
6. រង់ចាំ Process
7. ទាញយក វីដេអូ
---
⚠️ កំណត់សំខាន់
បញ្ហា ដំណោះស្រាយ
SharedArrayBuffer Error ត្រូវការ HTTPS ឬ localhost
Khmer Font មិនបង្ហាញ FFmpeg.wasm មានកំណត់ — ត្រូវ Download Font ដាក់
Process យឺត Browser-only គ្មាន GPU
វីដេអូធំ កំណត់ Max 100MB
Safari មិនដើរ ប្រើ Chrome/Firefox/Edge
---
🚨 បញ្ហា Khmer Font ក្នុង FFmpeg.wasm
បញ្ហា៖ FFmpeg.wasm មាន កំណត់ក្នុងការ Render អក្សរខ្មែរ ព្រោះ ៖
· FFmpeg ប្រើ Libfreetype ដែលមានកំណត់
· អក្សរខ្មែរត្រូវការ Complex Text Layout (CTL)
· FFmpeg.wasm មិនគាំទ្រ Harfbuzz ពេញលេញ
ដំណោះស្រាយ៖
✅ វិធីទី ១៖ ប្រើ Canvas API ជំនួស
```javascript
// Render Khmer text ដោយ Canvas រួចបញ្ចូលក្នុងវីដេអូ
function renderKhmerText(text, fontSize, color) {
const canvas = document.createElement('canvas');
canvas.width = 1280;
canvas.height = 720;
const ctx = canvas.getContext('2d');
ctx.font = `${fontSize}px Moul, Battambang, sans-serif`;
ctx.fillStyle = color;
ctx.textAlign = 'center';
ctx.strokeStyle = 'black';
ctx.lineWidth = 4;
const x = canvas.width / 2;
const y = canvas.height - 60;
ctx.strokeText(text, x, y);
ctx.fillText(text, x, y);
return canvas.toDataURL('image/png');
}
```
✅ វិធីទី ២៖ ប្រើ WebCodecs API
ប្រើ WebCodecs ដែលមានក្នុង Chrome ថ្មី ។
✅ វិធីទី ៣៖ ប្រើ Server-side
បើត្រូវការ Khmer Text ពិត គួរប្រើ Node.js + FFmpeg លើ Server ។
---
📋 ជំហានបន្ទាប់
1. ☐ Copy កូដទាំងអស់
2. ☐ Save ជា index.html
3. ☐ Run localhost server
4. ☐ សាកល្បង Upload វីដេអូ
5. ☐ សាកបន្ថែមអក្សរខ្មែរ
6. ☐ Download វីដេអូ
---
❓ តើអ្នកចង់ឲ្យខ្ញុំបន្ថែម?
· ☐ Khmer Text ដោយ Canvas (render ល្អជាង)?
· ☐ Watermark ជាមួយ Logo?
· ☐ Multiple Clips Merge?
· ☐ Audio Replace?
· ☐ Deploy លើ Netlify ជាជំហានៗ?
· ☐ Server-side Version (Node.js + FFmpeg ពេញលេច)?
ប្រាប់ខ្ញុំ ខ្ញុំនឹងជួយបន្ថែម! 🚀
No comments:
Post a Comment