audios.dart 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:soundpool/soundpool.dart';
  5. class Sound extends StatefulWidget {
  6. final Widget child;
  7. const Sound({Key? key, required this.child}) : super(key: key);
  8. @override
  9. SoundState createState() => SoundState();
  10. static SoundState of(BuildContext context) {
  11. final state = context.findAncestorStateOfType<SoundState>();
  12. assert(state != null, 'can not find Sound widget');
  13. return state!;
  14. }
  15. }
  16. const sounds = [
  17. 'clean.mp3',
  18. 'drop.mp3',
  19. 'explosion.mp3',
  20. 'move.mp3',
  21. 'rotate.mp3',
  22. 'start.mp3'
  23. ];
  24. class SoundState extends State<Sound> {
  25. late Soundpool _pool;
  26. final _soundIds = <String, int>{};
  27. bool mute = false;
  28. void _play(String name) {
  29. final soundId = _soundIds[name];
  30. if (soundId != null && !mute) {
  31. _pool.play(soundId);
  32. }
  33. }
  34. @override
  35. void initState() {
  36. super.initState();
  37. _pool =
  38. Soundpool.fromOptions(options: const SoundpoolOptions(maxStreams: 6));
  39. for (var value in sounds) {
  40. scheduleMicrotask(() async {
  41. final data = await rootBundle.load('assets/audios/$value');
  42. _soundIds[value] = await _pool.load(data);
  43. });
  44. }
  45. }
  46. @override
  47. void dispose() {
  48. super.dispose();
  49. _pool.dispose();
  50. }
  51. @override
  52. Widget build(BuildContext context) {
  53. return widget.child;
  54. }
  55. void start() {
  56. _play('start.mp3');
  57. }
  58. void clear() {
  59. _play('clean.mp3');
  60. }
  61. void fall() {
  62. _play('drop.mp3');
  63. }
  64. void rotate() {
  65. _play('rotate.mp3');
  66. }
  67. void move() {
  68. _play('move.mp3');
  69. }
  70. }