Skip to content

Audio

Examples#

example_1.py
import flet as ft

import flet_audio as fta


def main(page: ft.Page):
    url = "https://github.com/mdn/webaudio-examples/blob/main/audio-analyser/viper.mp3?raw=true"

    async def play(e: ft.Event[ft.ElevatedButton]):
        await audio.play()

    async def pause(e: ft.Event[ft.ElevatedButton]):
        await audio.pause()

    async def resume(e: ft.Event[ft.ElevatedButton]):
        await audio.resume()

    async def release(e: ft.Event[ft.ElevatedButton]):
        await audio.release()

    def set_volume(value: float):
        audio.volume += value

    def set_balance(value: float):
        audio.balance += value

    async def seek_2s(e: ft.Event[ft.ElevatedButton]):
        await audio.seek(ft.Duration(seconds=2))

    async def get_duration(e: ft.Event[ft.ElevatedButton]):
        duration = await audio.get_duration()
        print("Duration:", duration)

    async def on_get_current_position(e: ft.Event[ft.ElevatedButton]):
        position = await audio.get_current_position()
        print("Current position:", position)

    audio = fta.Audio(
        src=url,
        autoplay=False,
        volume=1,
        balance=0,
        on_loaded=lambda _: print("Loaded"),
        on_duration_change=lambda e: print("Duration changed:", e.duration),
        on_position_change=lambda e: print("Position changed:", e.position),
        on_state_change=lambda e: print("State changed:", e.state),
        on_seek_complete=lambda _: print("Seek complete"),
    )
    page.services.append(audio)

    page.add(
        ft.ElevatedButton("Play", on_click=play),
        ft.ElevatedButton("Pause", on_click=pause),
        ft.ElevatedButton("Resume", on_click=resume),
        ft.ElevatedButton("Release", on_click=release),
        ft.ElevatedButton("Seek 2s", on_click=seek_2s),
        ft.Row(
            controls=[
                ft.ElevatedButton("Volume down", on_click=lambda _: set_volume(-0.1)),
                ft.ElevatedButton("Volume up", on_click=lambda _: set_volume(0.1)),
            ]
        ),
        ft.Row(
            controls=[
                ft.ElevatedButton("Balance left", on_click=lambda _: set_balance(-0.1)),
                ft.ElevatedButton("Balance right", on_click=lambda _: set_balance(0.1)),
            ]
        ),
        ft.ElevatedButton("Get duration", on_click=get_duration),
        ft.ElevatedButton("Get current position", on_click=on_get_current_position),
    )


ft.run(main)

Audio #

Bases: Service

A control to simultaneously play multiple audio sources.

RAISES DESCRIPTION
AssertionError

If both src and src_base64 are None.

Note

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

autoplay #

autoplay: bool = False

Starts playing audio as soon as audio control is added to a page.

Note

Autoplay works in desktop, mobile apps and Safari browser, but doesn't work in Chrome/Edge.

balance #

balance: Number = 0.0

Defines the stereo balance.

  • -1 - The left channel is at full volume; the right channel is silent.
  • 1 - The right channel is at full volume; the left channel is silent.
  • 0 - Both channels are at the same volume.

data #

data: Any = skip_field()

Arbitrary data of any type.

key #

key: KeyValue | None = None

on_duration_change #

on_duration_change: (
    EventHandler[AudioDurationChangeEvent] | None
) = None

Fires as soon as audio duration is available (it might take a while to download or buffer it).

on_loaded #

on_loaded: ControlEventHandler[Audio] | None = None

Fires when an audio is loaded/buffered.

on_position_change #

on_position_change: (
    EventHandler[AudioPositionChangeEvent] | None
) = None

Fires when audio position is changed. Will continuously update the position of the playback every 1 second if the status is playing.

Can be used for a progress bar.

on_seek_complete #

on_seek_complete: ControlEventHandler[Audio] | None = None

Fires on seek completions. An event is going to be sent as soon as the audio seek is finished.

on_state_change #

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

Fires when audio player state 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.

playback_rate #

playback_rate: Number = 1.0

Defines the playback rate.

Should ideally be set when creating the constructor.

Note
  • iOS and macOS have limits between 0.5x and 2x.
  • Android SDK version should be 23 or higher.

release_mode #

release_mode: ReleaseMode = RELEASE

Defines the release mode.

src #

src: str | None = None

The audio source. Can be a URL or a local asset file.

Note
  • At least one of src or src_base64 must be provided, with src_base64 having priority if both are provided.
  • Here is a list of supported audio formats.

src_base64 #

src_base64: str | None = None

Defines the contents of audio file encoded in base-64 format.

Note
  • At least one of src or src_base64 must be provided, with src_base64 having priority if both are provided.
  • Here is a list of supported audio formats.

volume #

volume: Number = 1.0

Sets the volume (amplitude). It's value ranges between 0.0 (mute) and 1.0 (maximum volume). Intermediate values are linearly interpolated.

before_event #

before_event(e: ControlEvent)

before_update #

before_update()

build #

build()

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

did_mount #

did_mount()

get_current_position #

get_current_position(
    timeout: float | None = 10,
) -> Duration | None

Get the current position of the audio playback.

PARAMETER DESCRIPTION
timeout

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

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
Duration | None

The current position of the audio playback.

get_duration #

get_duration(timeout: float | None = 10) -> Duration | None

Get audio duration of the audio playback.

It will be available as soon as the audio duration is available (it might take a while to download or buffer it if file is not local).

PARAMETER DESCRIPTION
timeout

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

TYPE: float | None DEFAULT: 10

RETURNS DESCRIPTION
Duration | None

The duration of audio playback.

RAISES DESCRIPTION
TimeoutError

If the request times out.

init #

init()

is_isolated #

is_isolated()

pause #

pause(timeout: float | None = 10)

Pauses the audio that is currently playing.

If you call resume() later, the audio will resume from the point that it has been paused.

play #

play(
    position: DurationValue = 0, timeout: float | None = 10
)

Starts playing audio from the specified position.

PARAMETER DESCRIPTION
position

The position to start playback from.

TYPE: DurationValue DEFAULT: 0

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.

release #

release(timeout: float | None = 10)

Releases the resources associated with this media player. These are going to be fetched or buffered again as soon as you change the source or call resume().

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 #

resume(timeout: float | None = 10)

Resumes the audio that has been paused or stopped.

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.

seek #

seek(position: DurationValue, timeout: float | None = 10)

Moves the cursor to the desired position.

PARAMETER DESCRIPTION
position

The position to seek/move to.

TYPE: DurationValue

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.

update #

update() -> None

will_unmount #

will_unmount()