recreateNode method

void recreateNode()

Implementation

void recreateNode() {
  if (currentUrl.isEmpty) {
    return;
  }
  final web.HTMLAudioElement node = web.HTMLAudioElement();
  player = node;
  node.src = currentUrl;
  node.loop = playMode == PlayMode.single;
  node.volume = currentVolume;
  node.playbackRate = currentRate;
  // package:web 的事件属性/EventListener 是 JSFunction,不能直接赋 Dart 闭包,
  // 需用 dart:js_interop 的 .toJS 把 Dart 函数导出为 JS 函数。
  node.onloadedmetadata = ((web.Event _) {
    final duration = node.duration;
    if (duration.isFinite && duration > 0) {
      _emit('ready', (duration * 1000).round());
    }
  }).toJS;
  node.ontimeupdate = ((web.Event _) {
    final position = node.currentTime;
    final duration = node.duration;
    _emit('timeupdate', {
      'position': position.isFinite ? (position * 1000).round() : 0,
      'duration': duration.isFinite ? (duration * 1000).round() : 0,
    });
  }).toJS;
  node.onplay = ((web.Event _) {
    if (!identical(player, node)) return;
    isPlaying = true;
    _emit('playstatus', true);
  }).toJS;
  node.onpause = ((web.Event _) {
    if (!identical(player, node)) return;
    isPlaying = false;
    _emit('playstatus', false);
  }).toJS;
  node.onended = ((web.Event _) {
    if (!identical(player, node)) return;
    isPlaying = false;
    _emit('ended', null);
  }).toJS;
  node.addEventListener(
      'error',
      ((web.Event _) {
        _emit('error', node.error?.message ?? 'Web audio error');
      }).toJS);
}