我已经使用flutter_sound包来录制音频,音频也正在录制,但我无法从我使用audioplayers创建的音频播放器中播放音频。
以下是代码
class _ReviewBox extends State<ReviewBox> {
final recorder = FlutterSoundRecorder();
final audioPlayer = AudioPlayer();
bool isPlaying = false;
Duration duration = Duration.zero;
Duration position = Duration.zero;
bool isRecorderReady = false;
@override
void initState() {
super.initState();
initRecorder();
setAudio();
audioPlayer.onPlayerStateChanged.listen((state) {
setState(() {
isPlaying = state == PlayerState.playing;
});
});
// Listen to audio duration
audioPlayer.onDurationChanged.listen((newDuration) {
setState(() {
duration = newDuration;
});
});
// Listen to audio position
audioPlayer.onPositionChanged.listen((newPosition) {
setState(() {
position = newPosition;
});
});
}
Future setAudio() async {
// audioPlayer.setReleaseMode(ReleaseMode.stop);
final audioFile = await stop();
print(' audio file in setAudio :$audioFile');
if (audioFile != null) {
audioPlayer.setSource(
audioFile,
);
}
}
@override
void dispose() {
recorder.closeRecorder();
super.dispose();
}
Future initRecorder() async {
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw 'Microphone permission not granted';
}
await recorder.openRecorder();
isRecorderReady = true;
}
Future record() async {
if (!isRecorderReady) return;
await recorder.startRecorder(toFile: 'audio');
}
Future stop() async {
if (!isRecorderReady) return;
final path = await recorder.stopRecorder();
final audioFile = File(path!);
print('Recorded audio :$audioFile');
}
Future stop()方法停止音频记录器并将其保存为File类型。然后我调用了setAudio()方法的“audiofile”变量,这是另一个名为audioplayer的包中的函数,它将音频文件设置到音频播放器中以播放audiofile。
我也尝试过在setAudio方法中打印,但即使我在initState()中调用它,它也不会打印。
This is my DebugConsole Screenshot您可以在我的控制台中看到文件类型路径,当我播放和恢复录音机时,没有任何React。
1条答案
按热度按时间zpgglvta1#
我猜您是从本教程中获得这段代码的?https://www.youtube.com/watch?v=Bxn8k9F5JiM&t=13s&ab_channel=HeyFlutter%E2%80%A4com
我遇到了同样的问题。当你保存你的录音时,确保你包括了扩展名,否则音频播放器不会播放这个文件。