Packet-Exchange's picture
Add telephony audio preview tool
90f04f9 verified
Raw History Blame Contribute Delete
15.2 kB
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Telephony Audio Preview</title>
<style>
:root{
--bg:#0A0E14;
--panel:#111722;
--line:#1E2938;
--ink:#E8EDF5;
--muted:#93A1B5;
--brass:#E8C87E;
--brass-dim:#C9A85C;
}
*{box-sizing:border-box}
body{
margin:0;background:var(--bg);color:var(--ink);
font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
padding:32px 16px 64px;
}
.wrap{max-width:860px;margin:0 auto}
h1{font-size:26px;margin:0 0 6px;letter-spacing:-0.01em}
h2{font-size:15px;margin:0 0 14px;color:var(--brass);text-transform:uppercase;letter-spacing:.08em}
p{color:var(--muted);margin:0 0 14px}
.lede{color:var(--ink);font-size:16px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px;margin:18px 0}
.row{display:flex;flex-wrap:wrap;gap:12px;align-items:center}
button{
background:var(--brass);color:#14100A;border:0;border-radius:8px;
padding:10px 16px;font-weight:600;font-size:14px;cursor:pointer;
}
button.ghost{background:transparent;color:var(--brass);border:1px solid var(--brass-dim)}
button:disabled{opacity:.45;cursor:not-allowed}
label{display:block;font-size:13px;color:var(--muted);margin-bottom:6px}
select,input[type=file]{
background:#0C121C;color:var(--ink);border:1px solid var(--line);
border-radius:8px;padding:9px 10px;font-size:14px;width:100%;
}
input[type=range]{width:100%;accent-color:var(--brass)}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px}
.val{color:var(--brass);font-variant-numeric:tabular-nums}
audio{width:100%;margin-top:8px}
.note{font-size:13px;color:var(--muted)}
.bullets{color:var(--muted);padding-left:18px;margin:0 0 6px}
.bullets li{margin-bottom:8px}
a{color:var(--brass)}
footer{margin-top:28px;font-size:13px;color:var(--muted)}
#status{min-height:20px;font-size:13px;color:var(--brass);margin-top:10px}
canvas{width:100%;height:70px;display:block;background:#0C121C;border:1px solid var(--line);border-radius:8px;margin-top:10px}
</style>
</head>
<body>
<div class="wrap">
<h1>Telephony Audio Preview</h1>
<p class="lede">Hear what your speech model actually receives once the audio has been through a phone call.</p>
<p>Benchmarks are run on clean, wideband audio. A real call is narrowband, companded, and occasionally missing packets. This page applies that path to a sample of your own, entirely in your browser. Nothing is uploaded anywhere.</p>
<div class="card">
<h2>1. Load audio</h2>
<div class="grid">
<div>
<label for="file">Audio file (wav, mp3, m4a, ogg)</label>
<input type="file" id="file" accept="audio/*">
</div>
<div>
<label>Or use your microphone</label>
<div class="row">
<button id="rec" class="ghost">Record 5 seconds</button>
</div>
</div>
</div>
<canvas id="wave" width="1600" height="140" aria-label="Waveform of the loaded audio"></canvas>
<div id="status"></div>
</div>
<div class="card">
<h2>2. Choose the call path</h2>
<div class="grid">
<div>
<label for="codec">Codec and sample rate</label>
<select id="codec">
<option value="ulaw">G.711 u-law, 8 kHz (most PSTN calls)</option>
<option value="alaw">G.711 A-law, 8 kHz (Europe PSTN)</option>
<option value="lin8">Linear 8 kHz, no companding</option>
<option value="lin16">Wideband 16 kHz (HD voice)</option>
</select>
</div>
<div>
<label for="loss">Packet loss <span class="val" id="lossVal">0%</span></label>
<input type="range" id="loss" min="0" max="20" step="1" value="0">
</div>
<div>
<label for="burst">Loss burst length <span class="val" id="burstVal">1 packet</span></label>
<input type="range" id="burst" min="1" max="6" step="1" value="1">
</div>
<div>
<label for="conceal">Lost packet handling</label>
<select id="conceal">
<option value="silence">Silence (no concealment)</option>
<option value="repeat">Repeat previous packet</option>
</select>
</div>
</div>
<p class="note">Packets are 20 ms, the normal RTP payload size for these codecs.</p>
<div class="row" style="margin-top:14px">
<button id="go" disabled>Process</button>
<button id="playOrig" class="ghost" disabled>Play original</button>
<button id="dl" class="ghost" disabled>Download processed wav</button>
</div>
</div>
<div class="card">
<h2>3. Result</h2>
<audio id="out" controls></audio>
<p class="note" id="outNote">Load a sample and press Process.</p>
</div>
<div class="card">
<h2>Why this matters for voice agents</h2>
<ul class="bullets">
<li>Word error rates quoted on clean 16 kHz corpora do not carry over to 8 kHz companded audio. Test your recogniser on the band it will actually see.</li>
<li>Companding raises the noise floor in quiet passages, which is where endpointing and voice activity detection tend to make their mistakes.</li>
<li>Loss arrives in bursts rather than evenly. A 2 per cent loss figure that clusters into 100 ms gaps hurts turn detection far more than the same loss spread out.</li>
<li>Concealment choices matter. Repeating the previous packet keeps the energy contour plausible, silence does not, and your model hears the difference.</li>
<li>Fix the audio path before tuning the model. A lot of agents that sound broken on calls are fine in the notebook.</li>
</ul>
</div>
<footer>
Built by <a href="https://huggingface.co/PacketExchange">PacketExchange</a>, a voice, SMS and phone numbers platform for developers and AI agents.
Questions about the telephony side of a project are welcome at <a href="mailto:contact@packetexchange.io">contact@packetexchange.io</a>, whether or not you use our platform.
<br>Everything on this page runs locally in your browser.
</footer>
</div>
<script>
(function(){
"use strict";
var AC = window.AudioContext || window.webkitAudioContext;
var ctx = null;
var sourceBuffer = null; // decoded original, original rate
var processedWav = null; // Blob
var els = {
file: document.getElementById('file'),
rec: document.getElementById('rec'),
go: document.getElementById('go'),
playOrig: document.getElementById('playOrig'),
dl: document.getElementById('dl'),
out: document.getElementById('out'),
outNote: document.getElementById('outNote'),
status: document.getElementById('status'),
codec: document.getElementById('codec'),
loss: document.getElementById('loss'),
lossVal: document.getElementById('lossVal'),
burst: document.getElementById('burst'),
burstVal: document.getElementById('burstVal'),
conceal: document.getElementById('conceal'),
wave: document.getElementById('wave')
};
function audioCtx(){
if(!ctx) ctx = new AC();
if(ctx.state === 'suspended') ctx.resume();
return ctx;
}
function say(msg){ els.status.textContent = msg || ''; }
function ready(buf){
sourceBuffer = buf;
els.go.disabled = false;
els.playOrig.disabled = false;
drawWave(buf);
say('Loaded ' + buf.duration.toFixed(1) + ' s at ' + Math.round(buf.sampleRate) + ' Hz.');
}
function drawWave(buf){
var c = els.wave, g = c.getContext('2d');
var w = c.width, h = c.height;
g.clearRect(0,0,w,h);
var data = buf.getChannelData(0);
var step = Math.max(1, Math.floor(data.length / w));
g.strokeStyle = '#E8C87E'; g.lineWidth = 1.5; g.beginPath();
for(var x=0; x<w; x++){
var min=1, max=-1;
for(var i=0;i<step;i++){
var v = data[x*step+i] || 0;
if(v<min) min=v;
if(v>max) max=v;
}
g.moveTo(x, (1+min)*h/2);
g.lineTo(x, (1+max)*h/2);
}
g.stroke();
}
els.file.addEventListener('change', function(){
var f = els.file.files && els.file.files[0];
if(!f) return;
say('Decoding ' + f.name + ' ...');
var fr = new FileReader();
fr.onload = function(){
audioCtx().decodeAudioData(fr.result.slice(0)).then(ready).catch(function(e){
say('Could not decode that file. Try a wav or mp3.');
});
};
fr.readAsArrayBuffer(f);
});
els.rec.addEventListener('click', function(){
if(!navigator.mediaDevices || !window.MediaRecorder){
say('Recording is not supported in this browser.'); return;
}
navigator.mediaDevices.getUserMedia({audio:true}).then(function(stream){
var chunks = [], mr = new MediaRecorder(stream);
mr.ondataavailable = function(e){ if(e.data.size) chunks.push(e.data); };
mr.onstop = function(){
stream.getTracks().forEach(function(t){ t.stop(); });
var blob = new Blob(chunks, {type: chunks[0] ? chunks[0].type : 'audio/webm'});
blob.arrayBuffer().then(function(ab){
audioCtx().decodeAudioData(ab).then(ready).catch(function(){ say('Could not decode the recording.'); });
});
};
mr.start();
els.rec.disabled = true;
say('Recording, speak now ...');
setTimeout(function(){ mr.stop(); els.rec.disabled = false; }, 5000);
}).catch(function(){ say('Microphone permission was declined.'); });
});
els.loss.addEventListener('input', function(){ els.lossVal.textContent = els.loss.value + '%'; });
els.burst.addEventListener('input', function(){
els.burstVal.textContent = els.burst.value + (els.burst.value === '1' ? ' packet' : ' packets');
});
els.playOrig.addEventListener('click', function(){
if(!sourceBuffer) return;
var c = audioCtx(), s = c.createBufferSource();
s.buffer = sourceBuffer; s.connect(c.destination); s.start();
});
// --- G.711 ---------------------------------------------------------------
function ulawEncode(sample){
var BIAS = 0x84, CLIP = 32635, sign = (sample >> 8) & 0x80;
if(sign !== 0) sample = -sample;
if(sample > CLIP) sample = CLIP;
sample = sample + BIAS;
var exponent = 7, mask;
for(mask = 0x4000; (sample & mask) === 0 && exponent > 0; exponent--, mask >>= 1){}
var mantissa = (sample >> (exponent + 3)) & 0x0F;
return (~(sign | (exponent << 4) | mantissa)) & 0xFF;
}
function ulawDecode(u){
u = ~u & 0xFF;
var sign = u & 0x80, exponent = (u >> 4) & 0x07, mantissa = u & 0x0F;
var sample = ((mantissa << 3) + 0x84) << exponent;
sample -= 0x84;
return sign ? -sample : sample;
}
function alawEncode(sample){
var sign = ((~sample) >> 8) & 0x80, value;
if(!sign) sample = -sample;
if(sample > 32635) sample = 32635;
var exponent, mantissa;
if(sample >= 256){
exponent = 7;
for(var mask = 0x4000; (sample & mask) === 0 && exponent > 0; exponent--, mask >>= 1){}
mantissa = (sample >> (exponent + 3)) & 0x0F;
value = (exponent << 4) | mantissa;
} else {
value = sample >> 4;
}
return (value ^ sign ^ 0x55) & 0xFF;
}
function alawDecode(a){
a ^= 0x55;
var sign = a & 0x80, exponent = (a & 0x70) >> 4, mantissa = a & 0x0F, sample;
if(exponent === 0){
sample = (mantissa << 4) + 8;
} else {
sample = ((mantissa << 4) + 0x108) << (exponent - 1);
}
return sign ? -sample : sample;
}
function toInt16(f){
var v = Math.max(-1, Math.min(1, f));
return v < 0 ? v * 32768 : v * 32767;
}
function resample(buffer, rate){
var len = Math.max(1, Math.round(buffer.duration * rate));
var off = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)(1, len, rate);
var src = off.createBufferSource();
var mono = off.createBuffer(1, buffer.length, buffer.sampleRate);
var m = mono.getChannelData(0);
var chans = [];
for(var c = 0; c < buffer.numberOfChannels; c++) chans.push(buffer.getChannelData(c));
for(var i = 0; i < buffer.length; i++){
var sum = 0;
for(var j = 0; j < chans.length; j++) sum += chans[j][i];
m[i] = sum / chans.length;
}
src.buffer = mono;
src.connect(off.destination);
src.start();
return off.startRendering();
}
function wavBlob(samples, rate){
var bytes = samples.length * 2;
var buf = new ArrayBuffer(44 + bytes), v = new DataView(buf), o = 0;
function str(s){ for(var i=0;i<s.length;i++) v.setUint8(o++, s.charCodeAt(i)); }
function u32(x){ v.setUint32(o, x, true); o += 4; }
function u16(x){ v.setUint16(o, x, true); o += 2; }
str('RIFF'); u32(36 + bytes); str('WAVE'); str('fmt ');
u32(16); u16(1); u16(1); u32(rate); u32(rate * 2); u16(2); u16(16);
str('data'); u32(bytes);
for(var i = 0; i < samples.length; i++){
v.setInt16(44 + i * 2, Math.max(-32768, Math.min(32767, samples[i] | 0)), true);
}
return new Blob([buf], {type: 'audio/wav'});
}
els.go.addEventListener('click', function(){
if(!sourceBuffer) return;
var mode = els.codec.value;
var rate = (mode === 'lin16') ? 16000 : 8000;
var lossPct = parseInt(els.loss.value, 10);
var burst = parseInt(els.burst.value, 10);
var conceal = els.conceal.value;
say('Processing ...');
resample(sourceBuffer, rate).then(function(rendered){
var f = rendered.getChannelData(0);
var pcm = new Int16Array(f.length);
var i;
for(i = 0; i < f.length; i++){
var s = toInt16(f[i]);
if(mode === 'ulaw') s = ulawDecode(ulawEncode(s | 0));
else if(mode === 'alaw') s = alawDecode(alawEncode(s | 0));
pcm[i] = s;
}
// 20 ms packets, bursty loss
var pkt = Math.round(rate * 0.02);
var dropped = 0, total = Math.ceil(pcm.length / pkt), p = 0;
var prev = new Int16Array(pkt);
while(p < total){
var hit = Math.random() * 100 < lossPct;
if(hit){
var runs = burst;
while(runs-- > 0 && p < total){
var start = p * pkt, end = Math.min(start + pkt, pcm.length);
for(i = start; i < end; i++){
pcm[i] = (conceal === 'repeat') ? prev[i - start] : 0;
}
dropped++; p++;
}
} else {
var s0 = p * pkt, e0 = Math.min(s0 + pkt, pcm.length);
for(i = s0; i < e0; i++) prev[i - s0] = pcm[i];
p++;
}
}
processedWav = wavBlob(pcm, rate);
els.out.src = URL.createObjectURL(processedWav);
els.dl.disabled = false;
var pctLost = total ? (dropped / total * 100) : 0;
els.outNote.textContent = rate / 1000 + ' kHz, ' + els.codec.options[els.codec.selectedIndex].text.split(',')[0] +
', ' + dropped + ' of ' + total + ' packets lost (' + pctLost.toFixed(1) + '%).';
say('Done.');
}).catch(function(){ say('Processing failed on this file.'); });
});
els.dl.addEventListener('click', function(){
if(!processedWav) return;
var a = document.createElement('a');
a.href = URL.createObjectURL(processedWav);
a.download = 'telephony-preview.wav';
a.click();
});
})();
</script>
</body>
</html>