ukasz123 / soundpool

Soundpool plugin for Flutter
88 stars 63 forks source link

Not able to play sound at the start of a chrome web app #96

Closed erf closed 2 years ago

erf commented 2 years ago

Hi,

I'm building a Flutter app and i would like to play a sound at startup. This works fine on most platforms but not in Chrome. If i later press a button that plays a sound, the intro sound is played also.

I made a simple example:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:soundpool/soundpool.dart';

Soundpool soundPool = Soundpool.fromOptions();

int introSoundId = -1;
Future<void> initSounds() async {
  final bytes = await rootBundle.load('assets/sounds/intro.wav');
  introSoundId = await soundPool.load(bytes);
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initSounds();
  runApp(
    const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('Test sound_pool'),
        ),
      ),
    ),
  );

  Future.delayed(const Duration(milliseconds: 350), () {
    playIntroSound();
  });
}

void playIntroSound() async {
  await soundPool.play(introSoundId);
}

I'm on macOS.

I was able to play the intro sound in Firefox, but not in Safari.

I noticed Chrome logged the following warning issue:

The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://goo.gl/7K7WLu

The link seem to explain some new google policy. It seem i have to press a button in order to play a sound.

If you know a workaround for this it would be appreciated.

ukasz123 commented 2 years ago

Hi, @erf As far as I know there is no workaround (unless you somehow send the artificial click event to the browser). Safari also requires user interaction before allowing website to play a sound. So as you already know: user should press the button before accessing audio. You can see how I solved the problem in the example app.