我的代码用于在用户按下播放声音并且我需要一个按钮来停止播放音乐时播放歌曲。我之所以选择这样播放音乐,是因为由于某种原因,音频缓存功能无法在我的代码中起作用(我一直收到错误消息,提示无法加载文件),尽管这种方法有效,但我不知道如何停止这样播放音乐。
import 'dart:io';
import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:io';
class bodyscan extends StatefulWidget {
@override
_bodyscanState createState() => _bodyscanState();
}
enum PlayerState {stopped,playing,paused}
class _bodyscanState extends State<bodyscan> {
String mp3Uri = "";
void _playsound(){
AudioPlayer player = AudioPlayer();
player.play(mp3Uri);
}
void _loadsound() async {
final ByteData data = await rootBundle.load("audio/doomed.m4a");
Directory tempDir = await getTemporaryDirectory();
File tempFile = File('${tempDir.path}/doomed.m4a');
await tempFile.writeAsBytes(data.buffer.asUint8List(), flush:true);
mp3Uri = tempFile.uri.toString();
}
@override
void initState() {
_loadsound();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
enableFeedback: false,
child :Container (
color: Colors.blue,
padding: const EdgeInsets.all(20.0),
child: Text('PlaySound', style: TextStyle(color: Colors.white),) ,
),
onTap: _playsound,
),
],
),
)
);
}
}
答案 0 :(得分:1)
您刚刚尝试过 AudioPlayer player = new AudioPlayer();
String mp3Uri = "";
void _playSound() {
player.play(mp3Uri);
}
void _stopSound() {
player.stop();
}
吗?
如果它不起作用,那么也许您应该尝试将AudioPlayer从“ playMusic”方法移出外部,例如:
value
答案 1 :(得分:1)
如果使用 AudioCache 播放来自资产的音频文件,这是我找到的解决方案:
const timerFinishedAudio = "alarm-sound.mp3";
const audioFilesPrefix = 'audio/';
final audioPlayer = AudioPlayer();
// in your State
static AudioCache player = new AudioCache(prefix: audioFilesPrefix, fixedPlayer: audioPlayer);
// in a function
player.play(timerFinishedAudio);
// in another function or dispose()
audioPlayer.stop();
答案 2 :(得分:0)