简体   繁体   English

如何使用音频播放器 flutter 实现音频服务

[英]How to implement audio service with audioplayers flutter

Below code shows how i am using audioplayers without audio service下面的代码显示了我如何使用没有音频服务的音频播放器

playFromFile(List textList, seek) async {
    for (int i = seek; i < textList.length; i++) {
      setState(() {
        newSeek = i;
      });
      itemScrollController.scrollTo(
          index: i,
          duration: const Duration(seconds: 2),
          curve: Curves.easeInOutCubic);
      String text = textList[i].join(' ');
      final bytes = await getAudio(text);
      await audioPlugin.playBytes(bytes);
      while (audioPlugin.state == PlayerState.PLAYING && !playFresh) {
        await Future.delayed(const Duration(seconds: 1));
        if (audioPlugin.state == PlayerState.PLAYING) {
          audioPlugin.onPlayerCompletion.listen((onDone) async {
            audioPlugin.state = PlayerState.COMPLETED;
            await audioPlugin.release();
          });
        }
        if (audioPlugin.state == PlayerState.COMPLETED) {
          await audioPlugin.release();
          break;
        }
      }

      if (playFresh) break;
    }
  }

I want to implement this code using audio service so i can play audio in background.我想使用音频服务来实现这个代码,这样我就可以在后台播放音频。 How to implement this with audio service so it will play in background.如何使用音频服务实现此功能,以便在后台播放。 Please help as i am new to flutter and unable to solve this for days.请帮忙,因为我是 flutter 的新手,并且几天都无法解决这个问题。

Solution will be quite simple.解决方案将非常简单。 You implement this using different layer.您使用不同的层来实现它。

UI Layer - This will be your UI from where you going to click the play button. UI 层 - 这将是您单击播放按钮的 UI。

Intermediate layer or Audio service Layer(Audio service class) - From your UI layer you going to called this audio service class play method.中间层或音频服务层(音频服务类) - 从您的 UI 层,您将调用此音频服务 class 播放方法。

Final layer (Actual audio player methods) - This will be final layer where your actual audio package mehtods resides.最后一层(实际音频播放器方法)- 这将是您的实际音频 package 方法所在的最后一层。 You called this layer from your intermediate layer.您从中间层调用了这一层。

Summary - UI layer play button -> Audio service Play method -> Audio player Play method总结 - UI层播放按钮 -> 音频服务播放方法 -> 音频播放器播放方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM