I have written a Dart web app that retrieves .mp3 files from a server and plays them back; I am trying to write a mobile version using Flutter. I know dart:web_audio is the main option for a web app, but Flutter can't find it in my SDK. I know it's there because I can compile the following to Javascript:
import 'dart:html';
import 'dart:convert';
import 'dart:web_audio';
AudioContext audioContext;
main() async {
audioContext = new AudioContext();
var ul = (querySelector('#songs') as UListElement);
var signal = await HttpRequest.getString('http://10.0.0.6:8000/api/filelist');
// Map json = JSON.decode(signal);
// for (Map file in json['songs']) {
print("signal: $signal");
Map json = JSON.decode(signal);
for (Map file in json['songs']) {
var li = new LIElement()
..appendText(file['title']);
var button = new ButtonElement();
button.setAttribute("id", "#${file['file']}");
button.appendText("Play");
li.append(button);
new Song(button, file['file']);
ul.append(li);
}
}
class Song {
ButtonElement button;
bool _playing = false;
// AudioContext _audioContext;
AudioBufferSourceNode _source;
String title;
Song(this.button, this.title) {
button..onClick.listen((e) => _toggle());
}
_toggle() {
_playing = !_playing;
_playing ? _start() : _stop();
}
_start() {
return HttpRequest
.request("http://10.0.0.6:8000/music/$title", responseType: "arraybuffer")
.then((HttpRequest httpRequest) {
return audioContext
.decodeAudioData(httpRequest.response)
.then((AudioBuffer buffer) {
_source = audioContext.createBufferSource();
_source.buffer = buffer;
_source.connectNode(audioContext.destination);
_source.start(0);
button.text = "Stop";
_source.onEnded.listen((e){
_playing = false;
button.text = "Play";
});
});
});
}
_stop() {
_source.stop(0);
button.text = "Play";
}
}
How would I rewrite the dart:web_audio parts of my code for a Flutter app? Can Flutter access MediaPlayer? And if so, how would I refer to it in pubspec.yaml?
解决方案
As raju-bitter noted above, Flutter used to provide some built-in audio wrappers in its core engine but those have since been removed: https://github.com/flutter/flutter/issues/1364.
Flutter-using Apps are just iOS or Android apps, and thus it is possible to do anything the underlying iOS/Android can do via Flutter using some Java or Obj-C code in the hello_services model (https://github.com/flutter/flutter/tree/master/examples/hello_services). This model is documented at https://flutter.io/platform-services. It's not nearly as easy as we'd like it to be yet. Many improvements to come soon.