10.6 DTMF Example

Examples assume that sender is an RTCRtpSender.

Sending the DTMF signal “1234” with 500 ms duration per tone:

Example 13

  1. if (sender.dtmf.canInsertDTMF) {
  2. const duration = 500;
  3. sender.dtmf.insertDTMF('1234', duration);
  4. } else {
  5. console.log('DTMF function not available');
  6. }

Send the DTMF signal “123” and abort after sending “2”.

Example 14

  1. async function sendDTMF() {
  2. if (sender.dtmf.canInsertDTMF) {
  3. sender.dtmf.insertDTMF('123');
  4. await new Promise(r => sender.dtmf.ontonechange = e => e.tone == '2' && r());
  5. // empty the buffer to not play any tone after "2"
  6. sender.dtmf.insertDTMF('');
  7. } else {
  8. console.log('DTMF function not available');
  9. }
  10. }

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):

Example 15

  1. const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
  2. if (sender.dtmf.canInsertDTMF) {
  3. const duration = 500; // ms
  4. sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1234', duration);
  5. sender.dtmf.ontonechange = async ({tone}) => {
  6. if (!tone) return;
  7. lightKey(tone); // light up the key when playout starts
  8. await wait(duration);
  9. lightKey(''); // turn off the light after tone duration
  10. };
  11. } else {
  12. console.log('DTMF function not available');
  13. }

It is always safe to append to the tone buffer. This example appends before any tone playout has started as well as during playout.

Example 16

  1. if (sender.dtmf.canInsertDTMF) {
  2. sender.dtmf.insertDTMF('123');
  3. // append more tones to the tone buffer before playout has begun
  4. sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '456');
  5. sender.dtmf.ontonechange = ({tone}) => {
  6. // append more tones when playout has begun
  7. if (tone != '1') return;
  8. sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '789');
  9. };
  10. } else {
  11. console.log('DTMF function not available');
  12. }

Send a 1-second “1” tone followed by a 2-second “2” tone:

Example 17

  1. if (sender.dtmf.canInsertDTMF) {
  2. sender.dtmf.ontonechange = ({tone}) => {
  3. if (tone == '1') {
  4. sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '2', 2000);
  5. }
  6. };
  7. sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1', 1000);
  8. } else {
  9. console.log('DTMF function not available');
  10. }