You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用audioplayers开发木琴应用遇类型错误:String无法转为Source

解决audioplayers中play函数参数类型不匹配问题

你遇到的错误根源是audioplayers 1.x及以上版本的API变更:player.play()方法不再接受字符串路径,必须传入Source类型的对象(比如对应本地资源的AssetSource)。

错误信息明确提示:

"message": "The argument type 'String' can't be assigned to the parameter type 'Source'."

修正步骤:

  1. 配置音频资源
    确认note1.wav到note7.wav放在项目的assets目录下,然后在pubspec.yaml中声明资源:

    flutter:
      assets:
        - assets/note1.wav
        - assets/note2.wav
        - assets/note3.wav
        - assets/note4.wav
        - assets/note5.wav
        - assets/note6.wav
        - assets/note7.wav
        # 也可以用通配符简化:- assets/note*.wav
    
  2. 修改playSound函数
    将原来的字符串路径替换为AssetSource对象:

    void playSound(int soundNumber) async {
      final player = AudioPlayer();
      await player.play(AssetSource('note$soundNumber.wav'));
    }
    

    如果音频文件在assets的子目录(比如assets/audio/),路径要对应写成AssetSource('audio/note$soundNumber.wav')。

修正后的完整代码:

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

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

class XylophoneApp extends StatelessWidget {
  const XylophoneApp({super.key});

  void playSound(int soundNumber) async {
    final player = AudioPlayer();
    await player.play(AssetSource('note$soundNumber.wav'));
  }

  Expanded buildKey({Color? color, int? soundNumber}) {
    return Expanded(
      child: TextButton(
        style: TextButton.styleFrom(
          backgroundColor: color,
        ),
        onPressed: () {
          playSound(soundNumber!);
        },
        child: const Text(''),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.black,
        body: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              buildKey(color: Colors.red, soundNumber: 1),
              buildKey(color: Colors.orange, soundNumber: 2),
              buildKey(color: Colors.yellow, soundNumber: 3),
              buildKey(color: Colors.green, soundNumber: 4),
              buildKey(color: Colors.teal, soundNumber: 5),
              buildKey(color: Colors.blue, soundNumber: 6),
              buildKey(color: Colors.purple, soundNumber: 7),
            ],
          ),
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者Shashwat Rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:08:17