10.6 DTMF Example
Examples assume that sender is an RTCRtpSender
.
Sending the DTMF signal “1234” with 500 ms duration per tone:
if (sender.dtmf.canInsertDTMF) {
const duration = 500;
sender.dtmf.insertDTMF('1234', duration);
} else {
console.log('DTMF function not available');
}
Send the DTMF signal “123” and abort after sending “2”.
async function sendDTMF() {
if (sender.dtmf.canInsertDTMF) {
sender.dtmf.insertDTMF('123');
await new Promise(r => sender.dtmf.ontonechange = e => e.tone == '2' && r());
// empty the buffer to not play any tone after "2"
sender.dtmf.insertDTMF('');
} else {
console.log('DTMF function not available');
}
}
Send the DTMF signal “1234”, and light up the active key using lightKey(key)
while the tone is playing (assuming that lightKey("")
will darken all the keys):
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
if (sender.dtmf.canInsertDTMF) {
const duration = 500; // ms
sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1234', duration);
sender.dtmf.ontonechange = async ({tone}) => {
if (!tone) return;
lightKey(tone); // light up the key when playout starts
await wait(duration);
lightKey(''); // turn off the light after tone duration
};
} else {
console.log('DTMF function not available');
}
It is always safe to append to the tone buffer. This example appends before any tone playout has started as well as during playout.
if (sender.dtmf.canInsertDTMF) {
sender.dtmf.insertDTMF('123');
// append more tones to the tone buffer before playout has begun
sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '456');
sender.dtmf.ontonechange = ({tone}) => {
// append more tones when playout has begun
if (tone != '1') return;
sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '789');
};
} else {
console.log('DTMF function not available');
}
Send a 1-second “1” tone followed by a 2-second “2” tone:
if (sender.dtmf.canInsertDTMF) {
sender.dtmf.ontonechange = ({tone}) => {
if (tone == '1') {
sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '2', 2000);
}
};
sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1', 1000);
} else {
console.log('DTMF function not available');
}