【问题标题】:Play the audio each time the button is pressed - flutter每次按下按钮时播放音频 - 颤动
【发布时间】:2022-01-21 10:54:56
【问题描述】:

我的代码发生的情况是,当我第一次单击按钮时,音频会播放,但如果我再次单击它,音频不会播放。这里有什么问题?每次单击按钮时,我都想播放音频文件。这是我的代码-

import 'package:just_audio/just_audio.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late AudioPlayer player;
  @override
  void initState() {
    super.initState();
    player = AudioPlayer();
  }

  

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  await player.setAsset('assets/Audios/win.wav');
                  player.play();
                },
                child: const Text('Win'),
              ),
              
            ],
          ),
        ),
      ),
    );
  }
}

我正在为 Windows 平台在 Flutter 框架中构建这个应用程序。在 pubspec.yaml 文件中添加了“just_audio”依赖项,音频文件存储在 assets/Audios 目录下。

【问题讨论】:

  • 您违反了音频播放器的规则。在 initState 中设置源并在 onPress 按钮事件中再次播放之前停止播放器。
  • user-images.githubusercontent.com/19899190/… 查看你的库提供的生命周期图。
  • 我按照您在第一条评论中所说的进行了尝试,但并没有改变结果。我正在努力它的生命周期以及如何使用它。在这种情况下,可能是一个可以帮助我的例子。

标签: windows flutter dart audio just-audio


【解决方案1】:

试试下面的代码希望它对你有帮助。使用assets_audio_playerhere

你的功能:

  playSound() async { 
    AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();
    await audioPlayer.open(
      Audio(
        'assets/bells.mp3',
      ),
    );
  }

您的小部件:

   ElevatedButton(
        onPressed: () => playSound(),
        child: Text(
          'Play',
        ),
      ),

【讨论】:

  • 我也试过 assets_audio_player。但它没有用。此外,它与 Windows 平台不兼容。你在 Windows 中检查了吗?
  • 是的,它可以在 Mac 和 Widows 上运行
  • 我在 pubspec.yaml 文件中添加了 assets_audio_player: ^3.0.3+9 并面临以下错误-flutter: MissingPluginException(No implementation found for method stop on channel assets_audio_player)flutter: MissingPluginException(No implementation found for method open on channel assets_audio_player)[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method open on channel assets_audio_player)
  • 停止并重新启动您的应用,然后检查您的输出
  • 我在 google 中搜索过,已经尝试过了,得到了相同的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-28
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
相关资源
最近更新 更多