flet-dev / flet

Flet enables developers to easily build realtime web, mobile and desktop apps in Python. No frontend experience required.
https://flet.dev
Apache License 2.0
11.37k stars 446 forks source link

audio does not work on the web #3695

Open Gorkor227 opened 3 months ago

Gorkor227 commented 3 months ago

Duplicate Check

Describe the bug

audio does not work on the web.

Code sample

Logs ```python import flet as ft def main(page: ft.Page): audio1 = ft.Audio( src="https://luan.xyz/files/audio/ambient_c_motion.mp3", autoplay=True ) page.overlay.append(audio1) page.add( ft.Text("This is an app with background audio."), ft.ElevatedButton("Stop playing", on_click=lambda _: audio1.pause()), ft.ElevatedButton("playing", on_click=lambda _: audio1.play()), ) ft.app(target=main) ```

To reproduce

flet run --web

Expected behavior

No response

Screenshots / Videos

Screenshots / Video demonstration [Upload media here]

Operating System

Windows

Operating system details

Microsoft Windows 10 professional

Flet version

0.23.2

Regression

No, it isn't

Suggestions

No response

Logs

Logs ```console http://127.0.0.1:35886 ```

Additional details

my env: python 3.12.4

ndonkoHenri commented 3 months ago

Which web browser is that? and on which device?

Gorkor227 commented 3 months ago

那是哪种网络浏览器?在哪种设备上?

125.0.6422.61 chrome laptop win10

syleishere commented 3 months ago

Issue is browser not flet, if you run that code and inspect the web page, you will see your code is bad logic as browser is complaining about no user gesture so will not autoplay, which I believe was done years ago on purpose so ads cannot start playing on every website you visit.

Why not try something like this instead:

import flet as ft
from flet_core.types import AppView

class ConfigApp:
    def __init__(self, page):
        self.page = page
        # set audio to some empty wav file to get around gesture block for now
        self.audio = ft.Audio(src="https://mp3.sunsaturn.com/silent.wav", autoplay=True)
        self.page.overlay.append(self.audio)

    async def playme(self, e):
        self.audio.src = "https://luan.xyz/files/audio/ambient_c_motion.mp3"
        self.audio.play()
        self.audio.update()

async def main(page: ft.Page):
    config = ConfigApp(page)
    page.add(
        ft.Text("This is an app with background audio."),
        ft.ElevatedButton("Stop playing", on_click=lambda _: config.audio.pause()),
        ft.ElevatedButton("playing", on_click=config.playme),
    )

ft.app(target=main, view=AppView.WEB_BROWSER)

Should be noted when running any code in pure web form that remote site should have CORS enabled as well..

ndonkoHenri commented 3 months ago

autoplay was noted to have issues on chrome: https://flet.dev/docs/controls/audio/#:~:text=to%20False.-,NOTE,-Autoplay%20works%20in