|
| 1 | +"""Answer an incoming voice call using a WAV file, without audio devices.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | +import sys |
| 6 | + |
| 7 | +from aiortc.contrib.media import MediaPlayer |
| 8 | + |
| 9 | +from whatsapp_api_client_python.API import GreenAPI |
| 10 | +from whatsapp_api_client_python.tools.voip import CallAudio, FrameAudioSink |
| 11 | + |
| 12 | + |
| 13 | +async def make_audio() -> CallAudio: |
| 14 | + player = MediaPlayer(sys.argv[1]) |
| 15 | + |
| 16 | + if player.audio is None: |
| 17 | + raise ValueError("The file has no audio stream") |
| 18 | + |
| 19 | + async def on_frame(frame): |
| 20 | + # Replace this with your application's frame consumer. |
| 21 | + print(f"received {frame.samples} samples") |
| 22 | + |
| 23 | + sink = FrameAudioSink(on_frame) |
| 24 | + |
| 25 | + async def close(): |
| 26 | + await sink.closeAsync() |
| 27 | + player.audio.stop() |
| 28 | + |
| 29 | + return CallAudio(player.audio, sink.attachAsync, close) |
| 30 | + |
| 31 | + |
| 32 | +async def main(): |
| 33 | + api = GreenAPI(os.environ["GREEN_API_ID"], os.environ["GREEN_API_TOKEN"]) |
| 34 | + calls = api.voip.connect(audio_factory=make_audio) |
| 35 | + incoming = asyncio.Queue() |
| 36 | + ended = asyncio.Event() |
| 37 | + |
| 38 | + calls.on("incoming_call", incoming.put_nowait) |
| 39 | + calls.on("end_call", lambda detail: ended.set()) |
| 40 | + calls.on("error", lambda detail: print("Call error:", detail)) |
| 41 | + |
| 42 | + try: |
| 43 | + await calls.openAsync(timeout=30) |
| 44 | + |
| 45 | + info = await incoming.get() |
| 46 | + |
| 47 | + print("Incoming call:", info.wid) |
| 48 | + |
| 49 | + if calls.state is None or calls.state.state != "inc-call": |
| 50 | + return |
| 51 | + |
| 52 | + await api.voip.acceptAsync() |
| 53 | + await calls.startAudioAsync() |
| 54 | + await ended.wait() |
| 55 | + finally: |
| 56 | + await calls.closeAsync() |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + if len(sys.argv) != 2: |
| 61 | + raise SystemExit("Usage: incoming_call.py <audio.wav>") |
| 62 | + |
| 63 | + asyncio.run(main()) |
0 commit comments