Skip to content

AsyncStreamHandler breaks when no await is used in emit() #203

@vvolhejn

Description

@vvolhejn

Hi again! I tried generating a sine wave using AsyncStreamHandler but stumbled upon a strange issue - the server silently fails unless I add await asyncio.sleep(0.01) into the emit() method:

import asyncio

import numpy as np
from fastrtc import AsyncStreamHandler, Stream

SAMPLE_RATE = 24000
OUTPUT_FRAME_SIZE = 1920


class SineHandler(AsyncStreamHandler):
    def __init__(self) -> None:
        super().__init__(input_sample_rate=SAMPLE_RATE)
        self.cur_time_samples = 0

    async def receive(self, frame: tuple[int, np.ndarray]) -> None:
        pass

    async def emit(self) -> tuple[int, np.ndarray]:
        times = np.arange(
            self.cur_time_samples,
            self.cur_time_samples + OUTPUT_FRAME_SIZE,
        )
        x = np.sin(2 * np.pi * 440 / SAMPLE_RATE * times) * 0.3
        x = x.astype(np.float32)
        self.cur_time_samples += OUTPUT_FRAME_SIZE

        # Uncomment to fix:
        # await asyncio.sleep(0.01)

        return (SAMPLE_RATE, x)

    def copy(self):
        return SineHandler()

    async def start_up(self) -> None:
        pass


if __name__ == "__main__":
    stream = Stream(
        handler=SineHandler(),
        modality="audio",
        mode="send-receive",
    )

    stream.ui.launch(debug=True)

(Side note - when I add the sleep(), I still get audio artifacts, see #202 )

Screen.Recording.2025-03-21.at.12.48.15.mov

FastRTC version 0.0.17, Arc browser (Chromium-based), MacOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions