颤振-当我转到PianoMain页面时,音频只播放一次



我正在制作钢琴应用程序作为初学者的演示。我已经为钢琴制作了整个页面,包括UI和音频功能。但是,问题是,当我打开PianoMain,所以,它播放任何一个键的音频。然后,如果我按任何键的onTap它不工作。我把代码写在这里。还有,请检查一下是否能发现我的错误。

AudioPlayer player = AudioPlayer();
void playAudio({required String fileName}) {
player.play(AssetSource(fileName));
}

包是:import 'package:audioplayers/audioplayers.dart';

@override
void dispose() async {
super.dispose();
await player.stop();
}
Row(
children: [
PianoButtonSuperKey(
keyPress: () {
playAudio(fileName: "piano/piano3.mp3");
},
),
PianoButton(
onSuperKeyPress: () {
playAudio(fileName: "piano/blackpiano1.mp3");
},
onMainKeyPress: () {
playAudio(fileName: "piano/piano4.mp3");
},
),
PianoButtonSuperKey(
keyPress: () {
playAudio(fileName: "piano/piano5.mp3");
},
),
PianoButton(
onSuperKeyPress: () {
playAudio(fileName: "piano/hard7.mp3");
},
onMainKeyPress: () {
playAudio(fileName: "piano/piano10.mp3");
},
),
PianoButton(
onSuperKeyPress: () {
playAudio(fileName: "piano/hardpiano8.mp3");
},
onMainKeyPress: () {
playAudio(fileName: "piano/audio6.mp3");
},
),
],
),
class PianoButton extends StatelessWidget {
const PianoButton(
{super.key, required this.onMainKeyPress, required this.onSuperKeyPress});
final Function onMainKeyPress;
final Function onSuperKeyPress;
@override
Widget build(BuildContext context) {
return Expanded(
flex: 1,
child: Stack(
clipBehavior: Clip.none,
children: [
Container(
height: double.infinity,
width: double.infinity,
padding: const EdgeInsets.only(right: 8, bottom: 2, top: 2),
child: GestureDetector(
onTap: onMainKeyPress(),
child: Container(
decoration: const BoxDecoration(
color: Colors.white, boxShadow: [BoxShadow(blurRadius: 2)]),
),
),
),
Positioned(
top: 2,
right: 98,
child: SizedBox(
width: 50,
height: 200,
child: GestureDetector(
onTap: onSuperKeyPress(),
child: Container(
decoration: const BoxDecoration(color: Colors.black),
),
),
],
),
);
}
}
class PianoButtonSuperKey extends StatelessWidget {
const PianoButtonSuperKey({super.key, required this.keyPress});
final Function keyPress;
@override
Widget build(BuildContext context) {
return Expanded(
flex: 1,
child: Container(
height: double.infinity,
width: double.infinity,
padding: const EdgeInsets.only(right: 8, bottom: 2, top: 2),
child: GestureDetector(
onTap: keyPress(),
child: Container(
decoration: const BoxDecoration(
color: Colors.white, boxShadow: [BoxShadow(blurRadius: 2)]),
),
),
),
);
}
}

我希望我能清楚。

看起来你正在调用函数onMainKeyPress和onSuperKeyPress with()在你的手势检测器的onTap方法。这将导致函数在构建小部件时立即执行,而不是在点击小部件时执行。

要解决这个问题,你可以在调用你的gestredetector的onTap方法中的函数时删除()。例如,将onTap: onMainKeyPress()修改为onTap: onMainKeyPress。同样,将onTap: onSuperKeyPress()改为onTap: onSuperKeyPress。

相关内容

  • 没有找到相关文章

最新更新