如何在flutter中使用包audioplayers播放声音

问题描述 投票:0回答:2

我正在学习颤振课程。我试图在颤振中播放声音。

遗憾的是,我遇到以下错误代码

这是我的完整代码

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

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

class XylophoneApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
              child: TextButton(
                  onPressed: () async {
                    final player=AudioPlayer();
                    await player.play(AssetSource('sounds/note1.wav'));
                   },
                  child: const Text('Click Me'))),
        ),
      ),
    );
  }
}

这是我的 pubspec.yaml 文件设置

dependencies:
  audioplayers: ^1.1.1

assets:
  - sounds/

这是我的错误:

****[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: assets/sounds/note1.wav
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:258:7)
<asynchronous suspension>
#1      AudioCache.fetchToMemory (package:audioplayers/src/audio_cache.dart:75:22)
<asynchronous suspension>
#2      AudioCache.load (package:audioplayers/src/audio_cache.dart:101:31)
<asynchronous suspension>
#3      AudioPlayer.setSourceAsset (package:audioplayers/src/audioplayer.dart:237:17)
<asynchronous suspension>
#4      AudioPlayer.play (package:audioplayers/src/audioplayer.dart:123:5)
<asynchronous suspension>
#5      XylophoneApp.build.<anonymous closure> (package:xylophone1/main.dart:16:21)
<asynchronous suspension>****

我只需要使用这个音频播放器包来播放声音。

我更改了 pubspec.yaml 设置和文件夹名称“assets” 我还更改了此行的源代码以等待“player.play(AssetSource('note1.wav'));”

flutter dart audio audio-player
2个回答
0
投票

Audioplayers
在文件路径前面添加
assets/
。这就是你得到例外的原因:

Exception: Unable to load asset: assets/sounds/note1.wav

Audioplayers
希望您将
assets
作为资产的根文件夹。换句话说,在您的
pubspec.yaml
中您应该具有以下内容:

 assets: 
   - assets/sounds/

然后将所有音频文件放入

sounds
文件夹中。无需在 pubspec 中指定每个文件。

将您的播放器放在单独的类/库中,以实现可重用性和可读性:

player.dart

import 'package:audioplayers/audioplayers.dart';

class Player {
  static play(String src) async {
    final player = AudioPlayer();
    await player.play(AssetSource(src));
  }
}

称呼它:

onPressed: () {
    Player.play('sounds/note1.wav');
}

0
投票

只需更新 pubspec.yaml 文件,在路径中的声音之前添加资源

  assets:
    - assets/sounds/

并运行 flutter pub get

© www.soinside.com 2019 - 2024. All rights reserved.