Skip to content

AudioRecorder

Examples#

Example 1#

example_1.py
import flet as ft

import flet_audio_recorder as far


def main(page: ft.Page):
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.appbar = ft.AppBar(title=ft.Text("Audio Recorder"), center_title=True)

    path = "test-audio-file.wav"

    def show_snackbar(message):
        page.show_dialog(ft.SnackBar(ft.Text(message)))

    async def handle_recording_start(e: ft.Event[ft.Button]):
        show_snackbar("Starting recording...")
        await recorder.start_recording(output_path=path)

    async def handle_recording_stop(e: ft.Event[ft.Button]):
        output_path = await recorder.stop_recording()
        show_snackbar(f"Stopped recording. Output Path: {output_path}")
        if page.web and output_path is not None:
            await page.launch_url(output_path)

    async def handle_list_devices(e: ft.Event[ft.Button]):
        o = await recorder.get_input_devices()
        show_snackbar(f"Input Devices: {', '.join([d.label for d in o])}")

    async def handle_has_permission(e: ft.Event[ft.Button]):
        try:
            status = await recorder.has_permission()
            show_snackbar(f"Audio Recording Permission status: {status}")
        except Exception as e:
            show_snackbar(f"Error checking permission: {e}")

    async def handle_pause(e: ft.Event[ft.Button]):
        print(f"isRecording: {await recorder.is_recording()}")
        if await recorder.is_recording():
            await recorder.pause_recording()

    async def handle_resume(e: ft.Event[ft.Button]):
        print(f"isPaused: {await recorder.is_paused()}")
        if await recorder.is_paused():
            await recorder.resume_recording()

    async def handle_audio_encoder_test(e: ft.Event[ft.Button]):
        print(await recorder.is_supported_encoder(far.AudioEncoder.WAV))

    recorder = far.AudioRecorder(
        configuration=far.AudioRecorderConfiguration(encoder=far.AudioEncoder.WAV),
        on_state_change=lambda e: print(f"State Changed: {e.data}"),
    )
    page.services.append(recorder)

    page.add(
        ft.Button(content="Start Audio Recorder", on_click=handle_recording_start),
        ft.Button(content="Stop Audio Recorder", on_click=handle_recording_stop),
        ft.Button(content="List Devices", on_click=handle_list_devices),
        ft.Button(content="Pause Recording", on_click=handle_pause),
        ft.Button(content="Resume Recording", on_click=handle_resume),
        ft.Button(content="WAV Encoder Support", on_click=handle_audio_encoder_test),
        ft.Button(
            content="Get Audio Recording Permission Status",
            on_click=handle_has_permission,
        ),
    )


ft.run(main)

AudioRecorder #

Bases: Service

A control that allows you to record audio from your device.

This control can record audio using different audio encoders and also allows configuration of various audio recording parameters such as noise suppression, echo cancellation, and more.

Note

This control is non-visual and should be added to Page.services list before it can be used.

configuration #

configuration: AudioRecorderConfiguration = field(
    default_factory=lambda: AudioRecorderConfiguration()
)

The default configuration of the audio recorder.

data #

data: Any = skip_field()

Arbitrary data of any type.

key #

key: KeyValue | None = None

on_state_change #

on_state_change: (
    EventHandler[AudioRecorderStateChangeEvent] | None
) = None

Event handler that is called when the state of the audio recorder changes.

page #

page: Page | BasePage | None

The page to which this control belongs to.

parent #

parent: BaseControl | None

The direct ancestor(parent) of this control.

It defaults to None and will only have a value when this control is mounted (added to the page tree).

The Page control (which is the root of the tree) is an exception - it always has parent=None.

before_event #

before_event(e: ControlEvent)

before_update #

before_update()

This method is called every time when this control is being updated.

/// details | Note Make sure not to call/request an update() here. ///

build #

build()

Called once during control initialization to define its child controls. self.page is available in this method.

cancel_recording #

cancel_recording(timeout: float | None = 10)

Cancels the current audio recording.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RAISES DESCRIPTION
TimeoutError

If the request times out.

did_mount #

did_mount()

get_input_devices #

get_input_devices(
    timeout: float | None = 10,
) -> list[InputDevice]

Retrieves the available input devices for recording.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
list[InputDevice]

A list of available input devices.

RAISES DESCRIPTION
TimeoutError

If the request times out.

has_permission #

has_permission(timeout: float | None = 10) -> bool

Checks if the app has permission to record audio.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
bool

True if the app has permission, False otherwise.

RAISES DESCRIPTION
TimeoutError

If the request times out.

init #

init()

is_isolated #

is_isolated()

is_paused #

is_paused(timeout: float | None = 10) -> bool

Checks whether the audio recorder is currently paused.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
bool

True if the recorder is paused, False otherwise.

RAISES DESCRIPTION
TimeoutError

If the request times out.

is_recording #

is_recording(timeout: float | None = 10) -> bool

Checks whether the audio recorder is currently recording.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
bool

True if the recorder is currently recording, False otherwise.

RAISES DESCRIPTION
TimeoutError

If the request times out.

is_supported_encoder #

is_supported_encoder(
    encoder: AudioEncoder, timeout: float | None = 10
) -> bool

Checks if the given audio encoder is supported by the recorder.

PARAMETER DESCRIPTION
encoder

The audio encoder to check.

TYPE: AudioEncoder

timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
bool

True if the encoder is supported, False otherwise.

RAISES DESCRIPTION
TimeoutError

If the request times out.

pause_recording #

pause_recording(timeout: float | None = 10)

Pauses the ongoing audio recording.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RAISES DESCRIPTION
TimeoutError

If the request times out.

resume_recording #

resume_recording(timeout: float | None = 10)

Resumes a paused audio recording.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RAISES DESCRIPTION
TimeoutError

If the request times out.

start_recording #

start_recording(
    output_path: str | None = None,
    configuration: AudioRecorderConfiguration | None = None,
    timeout: float | None = 10,
) -> bool

Starts recording audio and saves it to the specified output path.

If not on the web, the output_path parameter must be provided.

PARAMETER DESCRIPTION
output_path

The file path where the audio will be saved. It must be specified if not on web.

TYPE: str | None DEFAULT: None

configuration

The configuration for the audio recorder. If None, the AudioRecorder.configuration will be used.

TYPE: AudioRecorderConfiguration | None DEFAULT: None

timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
bool

True if recording was successfully started, False otherwise.

RAISES DESCRIPTION
TimeoutError

If the request times out.

stop_recording #

stop_recording(timeout: float | None = 10) -> str | None

Stops the audio recording and optionally returns the path to the saved file.

PARAMETER DESCRIPTION
timeout

The maximum amount of time (in seconds) to wait for a response.

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
str | None

The file path where the audio was saved or None if not applicable.

RAISES DESCRIPTION
TimeoutError

If the request times out.

update #

update() -> None

will_unmount #

will_unmount()