简体   繁体   English

flutter如何在同一页面播放多个音频文件?

[英]How to play more than one audio file in the same page in flutter?

I have a chat page where a user can send texts, images, audio and video as messages to the other users.我有一个聊天页面,用户可以在其中将文本、图像、音频和视频作为消息发送给其他用户。 Everything works fine except for the Audio and Video.除音频和视频外,一切正常。 In my chat application, a user is allowed to pick audio files using the file_picker plugin.在我的聊天应用程序中,允许用户使用 file_picker 插件选择音频文件。 After the user picks an audio file, it is then uploaded to a server.用户选择音频文件后,将其上传到服务器。 The server than sends back the audio file using a socket event.服务器然后使用套接字事件发回音频文件。 My app listens to the socket event and generates the message view depending on the type of messages.我的应用程序侦听套接字事件并根据消息类型生成消息视图。 If its a text message, it is shown in a text widget.如果是文本消息,则会显示在文本小部件中。 If its a audio message, it is shown in an audio widget.如果它是音频消息,它会显示在音频小部件中。 audio_player plugin is used to play the audio file. audio_player 插件用于播放音频文件。 When the user uploads an audio, after a little time the audio file is shown to both the users chatting in the same room.当用户上传音频时,一段时间后,音频文件会显示给在同一个房间聊天的两个用户。 Everything works fine if it is a single audio file.如果它是单个音频文件,一切正常。 If the user uploads another audio file as in a 2nd audio, the audio controller replaces all my audio files in the chat view with the last audio uploaded.如果用户在第二个音频中上传另一个音频文件,音频 controller 会用最后上传的音频替换我在聊天视图中的所有音频文件。 The code used for audio is below:用于音频的代码如下:

    //for audio files (This code has been placed in _ChatPageState)
  AnimationController _animationIconController1;
  AudioCache audioCache;
  AudioPlayer audioPlayer;
  Duration _duration = new Duration();
  Duration _position = new Duration();
  Duration _slider = new Duration(seconds: 0);
  double durationValue;
  bool isSongPlaying = false;
  bool isPlaying = false;

Later, the variables are initialsed in initState()稍后,变量在 initState() 中初始化

//for audio inside initState
_position = _slider;
_animationIconController1 = AnimationController(
  vsync: this,
  duration: Duration(milliseconds: 750),
  reverseDuration: Duration(milliseconds: 750),
);
audioPlayer = new AudioPlayer();
audioCache = new AudioCache(fixedPlayer: audioPlayer);
audioPlayer.durationHandler = (d) => setState(() {
  _duration = d;
});

audioPlayer.positionHandler = (p) => setState(() {
  _position = p;
});

Next, if the user receives a audio file from socket listener an audio widget is presented, so that the users can play the file:接下来,如果用户从套接字侦听器接收到音频文件,则会显示一个音频小部件,以便用户可以播放该文件:

Widget audioMessage(int index) {
return Container(
  width: MediaQuery.of(context).size.width * 0.6,
  height: 30,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      GestureDetector(
        onTap: () {
          setState(() {
            isPlaying ? _animationIconController1.reverse() : _animationIconController1.forward();
            isPlaying = !isPlaying;
          });
          // Add code to pause and play the music.
          if (!isSongPlaying){
            audioPlayer.play('some hidden link/file/${messages[index].message}');
            setState(() {
              isSongPlaying = true;
            });
          } else {
            audioPlayer.pause();
            setState(() {
              isSongPlaying = false;
            });
          }
        },
        child: ClipOval(
          child: Container(
            color: Colors.pink[600],
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: AnimatedIcon(
                icon: isSongPlaying ==false ? AnimatedIcons.play_pause : AnimatedIcons.pause_play,
                size: 14,
                progress: _animationIconController1,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
      Slider(
        activeColor: Colors.white,
        inactiveColor: Colors.grey,
        value: _position.inSeconds.toDouble(),
        max: _duration.inSeconds.toDouble(),
        onChanged: (double value) {
          seekToSeconds(value.toInt());
          value = value;
        },
      ),
    ],
  ),
);

} }

I think the problem is with my audio and animation controllers.我认为问题出在我的音频和 animation 控制器上。 It is only initiated for only one player.它仅针对一名玩家启动。 So how can i go around this problem.那么我该如何解决这个问题。 A user can upload as many audios as he wants.用户可以上传任意数量的音频。 How can i dynamically create audio controllers for as many audio files that are uploaded by the user?如何为用户上传的尽可能多的音频文件动态创建音频控制器?

So, I have accomplished this by moving all my audio codes into a separate dart file.因此,我通过将我所有的音频代码移动到一个单独的 dart 文件中来实现这一点。 See below for audio implementation:音频实现见下文:

  class PlayAudio extends StatefulWidget {
  final String url;
  
  const PlayAudio({Key key, this.url}) : super(key: key);

  @override
  _PlayAudioState createState() => _PlayAudioState();
}

class _PlayAudioState extends State<PlayAudio> with TickerProviderStateMixin{
  //for audio files
  AnimationController _animationIconController1;
  AudioCache audioCache;
  AudioPlayer audioPlayer;
  Duration _duration = new Duration();
  Duration _position = new Duration();
  Duration _slider = new Duration(seconds: 0);
  double durationValue;
  bool isSongPlaying = false;
  bool isPlaying = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //for audio inside initState
    _position = _slider;
    _animationIconController1 = new AnimationController(
      vsync: this,
      duration: new Duration(milliseconds: 750),
      reverseDuration: new Duration(milliseconds: 750),
    );
    audioPlayer = new AudioPlayer();
    audioCache = new AudioCache(fixedPlayer: audioPlayer);
    audioPlayer.durationHandler = (d) => setState(() {
      _duration = d;
    });

    audioPlayer.positionHandler = (p) => setState(() {
      _position = p;
    });

    print('audio widget: ' + widget.url);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    audioPlayer.dispose();
  }

  void seekToSeconds(int second) {
    Duration newDuration = Duration(seconds: second);
    audioPlayer.seek(newDuration);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width * 0.6,
      height: 30,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                isPlaying ? _animationIconController1.reverse() : _animationIconController1.forward();
                isPlaying = !isPlaying;
              });
              // Add code to pause and play the music.
              if (!isSongPlaying){
                audioPlayer.play('${widget.url}');
                setState(() {
                  isSongPlaying = true;
                });
              } else {
                audioPlayer.pause();
                setState(() {
                  isSongPlaying = false;
                });
              }
            },
            child: ClipOval(
              child: Container(
                color: Colors.pink[600],
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: AnimatedIcon(
                    icon: AnimatedIcons.play_pause,
                    size: 14,
                    progress: _animationIconController1,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          Slider(
            activeColor: Colors.white,
            inactiveColor: Colors.grey,
            value: _position.inSeconds.toDouble(),
            max: _duration.inSeconds.toDouble(),
            onChanged: (double value) {
              seekToSeconds(value.toInt());
              value = value;
            },
          ),
        ],
      ),
    );
  }
}

This is now a separate class.现在这是一个单独的 class。 Now, to play multiple audio files all I am doing is calling the above file into my main.dart wherever it is needed.现在,要播放多个音频文件,我所做的就是在需要的地方将上述文件调用到我的 main.dart 中。 Make sure you call 'new' everytime you want to play a new audio file, just pass an url.确保每次要播放新的音频文件时都调用“new”,只需传递 url。 See below:见下文:

new PlayAudio(url: 'some URL');

Hope this helps to play multiple audio files in the same page.希望这有助于在同一页面中播放多个音频文件。 FYI, i am using https://pub.dev/packages/audioplayers仅供参考,我正在使用https://pub.dev/packages/audioplayers

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

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