简体   繁体   English

flutter:: 有没有办法使用音频播放器 package 只播放一个音频文件?

[英]flutter:: Is there a way to play only one audio file using the audioplayer package?

I saved the audio files in list 'file'.我将音频文件保存在列表“文件”中。 I want to play this audio file using the audioplayers package.我想使用音频播放器 package 播放此音频文件。 I have listed audio files using listview, but I want to play only one selected audio file among multiple audio files.我已经使用 listview 列出了音频文件,但我只想在多个音频文件中播放一个选定的音频文件。 Currently, the entire audio file in the records is played at the same time and an error has occurred.目前,同时播放记录中的整个音频文件,出现错误。
How can I solve this?我该如何解决这个问题?

This is part of my code.这是我的代码的一部分。

class AudioViewer extends StatefulWidget {
  @override
  _AudioViewerState createState() => _AudioViewerState();
}

class _AudioViewerState extends State<AudioViewer> {
  List file = [];
  var audioPath;
  var directory;
  AudioPlayer? audioPlayer;
  bool _isplaying = false;
  var _icon = Icons.play_arrow;
  var _deleteicon = Icons.delete;
  Color _color = Colors.deepOrangeAccent;
  Duration position = Duration();
  Duration duration = Duration(seconds: 1);

  int indexindex = 0;

  @override
  void initState() {
    super.initState();
    getFiles();
    _setupAudioPlayer();
  }

  void getFiles() async {
    directory = (await getExternalStorageDirectory())!.path;
    setState(() {
      file = Directory("$directory").listSync();
    });
    print(file.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "Audio List",
        ),
      ),
      body: Container(
          child: ListView.builder(
            reverse: true,
            itemCount: widget.records.length,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
            return Card(
                elevation: 5,
                child: ExpansionTile(
                    title: Text(
                      widget.records[index].path.split('/').last.split(".").first,
                      style: TextStyle(color: Colors.black),
                    ),
                    onExpansionChanged: ((newState) {
                      if (newState) {
                        indexindex = index;
                        setState(() {
                    
                        });
                      }
                    }),
                    children: [
                      Container(
                        height: 100,
                        padding: EdgeInsets.fromLTRB(10,0,10,0),
                        child: Column(
                          children: <Widget>[
                                Row(
                                    children: <Widget>[
                                      Container(
                                        child: IconButton(
                                          iconSize: 40,
                                        onPressed: () {
                                            if (!_isplaying) {
                                              audioPlayer!.resume();
                         setState(() {
                                                _isplaying = true;
                                                _icon = Icons.pause;
                                                _color = Colors.blueGrey;

                                              });
                                            } else {
                                              audioPlayer!.release();
                                              setState(() {
                                                position = new Duration();
                                                _isplaying = false;
                                                _icon = Icons.play_arrow;
                                                _color = Colors.deepOrangeAccent;

                                              });
                                            }
                                          },
                                          icon: Icon(_icon),
                                          color: _color,
                                        ),
                                      ),
                                      Container(
                                        child: IconButton(
                                          iconSize: 30,
                                          onPressed: () {
                                            widget.records[index].delete(recursive: true);
                                            setState(() {
                                              widget.records.removeAt(index);
                                              position = new Duration();
                                            });
                                          },
                                          icon: Icon(_deleteicon),
                                        ),
                                      ),
                                    ]
                                ),

It seems you have your state variables like _isplaying only once for the whole page/list.看来你有你的 state 变量,比如_isplaying整个页面/列表只有一次 You need them per song .每首歌都需要它们。 This doesn't seem to be a complete example ( widget.records seems to be missing) so I cannot really help a lot here.这似乎不是一个完整的例子( widget.records似乎丢失了)所以我在这里帮不上什么忙。

What you could do, if widget.records contains the songs, is to have a currentlyPlaying variable that is the record that is currently playing, instead of just a generic _isplaying .如果widget.records包含歌曲,您可以做的是拥有一个 currentPlaying 变量,它是currentlyPlaying正在播放的记录,而不仅仅是一个通用的_isplaying This way, you could figure out if the currectly build list entry is actually playing or not.这样,您可以确定当前构建列表条目是否正在播放。 But then maybe I'm misunderstanding something, since your audioplayer is not actually playing that song, it just resumes whatever it was playing before.但是也许我误解了一些东西,因为您的音频播放器实际上并没有播放那首歌,它只是恢复之前播放的任何内容。

Maybe start out with easy steps and first make the icon work.也许从简单的步骤开始,首先让图标工作。 That should be possible with the method I mentioned above: keep track of which record was selected.使用我上面提到的方法应该可以做到这一点:跟踪选择了哪个记录。

You need to create a globals.dart file like that:您需要像这样创建一个 globals.dart 文件:

AudioPlayer? _player;  

Future<void> playAudio(AudioPlayer player, AudioSource source) async {  
    if (_player != null && _player!.playing) {
      await _player!.stop();
    }
    _player = player;
    player.setAudioSource(source);
    player.play();
  

} }

And use it in somewhere:并在某处使用它:

playAudio(currentAudio, audioSource);

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

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