JS播放 DTMF

玩 WebRTC 的时候发现它居然内置支持了 DTMF 拨号音

这里就简单科普一下,DTMF 就是手机电话拨号音,数字按键按下去嘟嘟嘟响那个。具体就2个频率调谐:

DTMF 1209Hz 1336Hz 1477Hz 1633Hz
697Hz 1 2 3 A
770Hz 4 5 6 B
852Hz 7 8 9 C
941Hz * 0 # D

于是兴趣来了想做一个 demo 玩玩,写了半天调试不通,报错

VM987:1 Uncaught DOMException: Failed to execute 'insertDTMF' on 'RTCDTMFSender': The 'canInsertDTMF' attribute is false: this sender cannot send DTMF.

仔细研究了下这玩意,原来 WebRTC 不直接传音频,而是发一个控制信号,由接收方播放出音频,所以你需要本地创建一个真实的双工 RTC 并打开麦克风权限,才能播放DTMF音频。

WebRTC doesn't send DTMF codes as audio data. Instead, they're sent out-of-band, as RTP payloads. Note, however, that although it's possible to send DTMF using WebRTC, there is currently no way to detect or receive incoming DTMF. WebRTC currently ignores these payloads;

这样就走远了。于是又手痒用 AudioContext() 糊了一个。一共不到1000字节。

https://lab.est.im/dtmf 源码

嗯。就挺简单的。特别是那个 oscillator有个 .stop(0.2) 参数可以避免 setTimeout 的麻烦。网上很多教程整复杂了。

btw 把一些老脚本挂在 lab 域名下。
btw2 把 RSS 改成全文输出了。

Comments