颤动:打开页面后如何开始播放音频

时间:2020-11-09 10:32:45

标签: flutter dart

我正在尝试从打开的页面开始播放音频列表,但是即使我还没有打开页面,声音也在播放。 我该如何仅打开页面就播放声音

路线:

    void main() {
  runApp(MaterialApp(
    initialRoute: '/surasList',
    routes: {
      '/surasList': (content) => SurasList(),
      '/' : (context) => PlaySound(),
    },
  ));
}

在不打开声音的情况下启动声音的页面:

    class PlaySound extends StatefulWidget {

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

   class _PlaySoundState extends State<PlaySound> {

     List<WordSound> soundPathes = [
       WordSound(word: 'Alfalak' , wPath: 'alfalak'),
       WordSound(word: 'AlEkhlas' , wPath: 'alsamad'),
       WordSound(word: 'Alfalak' , wPath: 'alfalak'),
       WordSound(word: 'AlEkhlas' , wPath: 'alsamad'),
     ];

     final  assetsAudioPlayer = AssetsAudioPlayer();
     final player = AudioCache();
     bool isPressed = false;
     int m =0;

     @override
     void initState() {
       final soundMap = soundPathes.asMap();
       super.initState();
       openingActions() async { //add this
         assetsAudioPlayer.open(
             Audio("assets/audios/${soundMap[m].wPath}.mp3"));
       }
     }

     @override
     Widget build(BuildContext context) {
       final soundMap = soundPathes.asMap();

       return Scaffold(
         appBar: AppBar(
           title: Text('Play Sound'),
         ),
         body: Center(
           child: Column(
             children: [
                RaisedButton(


                   child: Text('Play'),
                   onPressed:(){
                     assetsAudioPlayer.stop();
                     bool playB = assetsAudioPlayer.isPlaying.value;
                     setState(() {
                       m = m +1;
                       assetsAudioPlayer.open(
                         Audio("assets/audios/${soundMap[m].wPath}.mp3"),
                       );

                     });


                   } ,
                 ),
               RaisedButton(
                 child: Text('stop'),
                 onPressed:(){
                   if(assetsAudioPlayer.isPlaying.value == true){assetsAudioPlayer.stop();}
                 } ,
               ),
               Text(
                 soundMap[m].word,
                 style: TextStyle (
                   fontSize: 28,
                 ),
               ),
             ],
           ),
         ),
       );
     }
   }

我如何只在打开声音页面时才能播放声音,而没有打开它就不能在后台播放声音

0 个答案:

没有答案