「請幫我寫一個錄音功能。」
嗯...程式碼立刻出來了。
但是不行,因為這個功能無法在網頁上順利執行。
final FlutterSoundRecorder _recorder = FlutterSoundRecorder();
Future<void> startRecording(String path) async {
await _recorder.openAudioSession();
await _recorder.startRecorder(toFile: path);
}
Future<void> stopRecording() async {
await _recorder.stopRecorder();
await _recorder.closeAudioSession();
}
Future<bool> isRecording() async {
// return await _recorder.isRecording();
return _recorder.isRecording;
}
「請幫我寫一個能在FlutterWeb執行的錄音功能。」
html.MediaRecorder? _mediaRecorder;
final _audioStreamController = StreamController<List<int>>();
Stream<List<int>> get audioStream => _audioStreamController.stream;
Future<void> startRecording() async {
final mediaStream = await html.window.navigator.mediaDevices?.getUserMedia({'audio': true});
_mediaRecorder = html.MediaRecorder(mediaStream!);
_mediaRecorder!.addEventListener('dataavailable', (event) {
final blobEvent = event as html.BlobEvent;
final reader = html.FileReader();
reader.readAsArrayBuffer(blobEvent.data!);
reader.onLoadEnd.listen((event) {
if (reader.readyState == html.FileReader.DONE && reader.result != null)
{
final data = reader.result as Uint8List;
_audioStreamController.add(data);
}
});
});
_mediaRecorder!.start();
}
void stopRecording() async {
_mediaRecorder?.stop();
_mediaRecorder = null;
}
哎呀呀!
應該要花點時間介紹物件導向了!