florent37 / Flutter-AssetsAudioPlayer

Play simultaneously music/audio from assets/network/file directly from Flutter, compatible with android / ios / web / macos, displays notifications
https://pub.dartlang.org/packages/assets_audio_player
Apache License 2.0
741 stars 337 forks source link

final isPlaying = this.isPlaying.valueOrNull ?? false; #593

Closed lyntree closed 2 years ago

lyntree commented 2 years ago

Flutter Version

My version : 2.2.3,

Lib Version

My version : (Android SDK version 30.0.3)

Platform (Android / iOS / web) + version

Platform : Android / IOS / Mac

Describe the bug

audioassetsbug.txt

Small code to reproduce

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';

// 1. Component - Radio
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:audiodamageradio/pages/player/Player_Controls.dart';
// import 'package:audiodamageradio/pages/player/Position_Seek.dart';
// import 'package:audiodamageradio/pages/player/Song_Selector.dart';
// import 'package:audiodamageradio/pages/player/AssetAudioIcons.dart';

// 2. Component - Menu Drawer
import 'package:audiodamageradio/components/drawer/menu.dart';

// 3. Component - In App Web View
// import 'package:flutter_inappwebview/flutter_inappwebview.dart';

// void main() {
//   AssetsAudioPlayer.setupNotificationsOpenAction((notification) {
//     print(notification.audioId);
//     return true;
//   });

//   runApp(
//     NeumorphicTheme(
//       theme: NeumorphicThemeData(
//         intensity: 0.8,
//         lightSource: LightSource.topLeft,
//       ),
//       child: MyApp(),
//     ),
//   );
// }

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final audios = <Audio>[
    Audio.network(
      'https://streaming.radio.co/s14d5f8cc0/low',
      metas: Metas(
        id: 'Online',
        title: 'Audio Damage Radio',
        artist: 'Now Playing',
        album: 'UKs Best No1 Underground Dance Station',
        // image: MetasImage.network('https://www.google.com')
        image: MetasImage.network(
            'https://audiodamage.co.uk/wp-content/uploads/2021/04/Untitled-design.png'),
      ),
    ),
  ];

  //final AssetsAudioPlayer _assetsAudioPlayer = AssetsAudioPlayer();
  AssetsAudioPlayer get _assetsAudioPlayer => AssetsAudioPlayer.withId('music');
  final List<StreamSubscription> _subscriptions = [];

  @override
  void initState() {
    super.initState();
    //_subscriptions.add(_assetsAudioPlayer.playlistFinished.listen((data) {
    //  print('finished : $data');
    //}));
    //openPlayer();
    _subscriptions.add(_assetsAudioPlayer.playlistAudioFinished.listen((data) {
      print('playlistAudioFinished : $data');
    }));
    _subscriptions.add(_assetsAudioPlayer.audioSessionId.listen((sessionId) {
      print('audioSessionId : $sessionId');
    }));
    _subscriptions
        .add(AssetsAudioPlayer.addNotificationOpenAction((notification) {
      return false;
    }));
    openPlayer();
  }

  void openPlayer() async {
    await _assetsAudioPlayer.open(
      Playlist(audios: audios, startIndex: 0),
      showNotification: true,
      autoStart: false,
    );
  }

  @override
  void dispose() {
    _assetsAudioPlayer.dispose();
    print('dispose');
    super.dispose();
  }

  Audio find(List<Audio> source, String fromPath) {
    return source.firstWhere((element) => element.path == fromPath);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.white,
        drawer: DrawerCodeOnly(),
        appBar:
            new AppBar(title: new Text('RADIO'), backgroundColor: Colors.black),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 48.0),
              child: Column(
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  SizedBox(
                    height: 40,
                  ),
                  Stack(
                    fit: StackFit.passthrough,
                    children: <Widget>[
                      _assetsAudioPlayer.builderCurrent(
                        builder: (BuildContext context, Playing playing) {
                          final myAudio =
                              find(audios, playing.audio.assetAudioPath);
                          return Padding(
                            padding: const EdgeInsets.all(15.0),
                            child: Neumorphic(
                              style: NeumorphicStyle(
                                // depth: 8,
                                // surfaceIntensity: 1,
                                // shape: NeumorphicShape.concave,
                                boxShape: NeumorphicBoxShape.circle(),
                                color: Colors.black,
                              ),
                              child: myAudio.metas.image?.path == null
                                  ? const SizedBox()
                                  : myAudio.metas.image?.type ==
                                          ImageType.network
                                      ? Image.network(
                                          myAudio.metas.image!.path,
                                          height: 180,
                                          width: 180,
                                          fit: BoxFit.contain,
                                        )
                                      : Image.asset(
                                          myAudio.metas.image!.path,
                                          height: 250,
                                          width: 250,
                                          fit: BoxFit.contain,
                                        ),
                            ),
                          );
                        },
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        // child: NeumorphicButton(
                        //   style: NeumorphicStyle(
                        //     boxShape: NeumorphicBoxShape.circle(),
                        //   ),
                        //   padding: EdgeInsets.all(18),
                        //   margin: EdgeInsets.all(18),
                        //   onPressed: () {
                        //     AssetsAudioPlayer.playAndForget(
                        //         Audio('assets/audios/horn.mp3'));
                        //   },
                        //   child: Icon(
                        //     Icons.add_alert,
                        //     color: Colors.grey[800],
                        //   ),
                        // ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 120,
                  ),
                  Text(
                    'Press to Listen',
                    style: TextStyle(
                      fontFamily: 'RobotoMono',
                      fontSize: 40.0,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  SizedBox(
                    height: 60,
                  ),
                  _assetsAudioPlayer.builderCurrent(
                      builder: (context, Playing? playing) {
                    return Column(
                      children: <Widget>[
                        _assetsAudioPlayer.builderLoopMode(
                          builder: (context, loopMode) {
                            return PlayerBuilder.isPlaying(
                                player: _assetsAudioPlayer,
                                builder: (context, isPlaying) {
                                  return PlayingControls(
                                    loopMode: loopMode,
                                    isPlaying: isPlaying,
                                    isPlaylist: true,
                                    onStop: () {
                                      _assetsAudioPlayer.stop();
                                    },
                                    toggleLoop: () {
                                      _assetsAudioPlayer.toggleLoop();
                                    },
                                    onPlay: () {
                                      _assetsAudioPlayer.playOrPause();
                                    },
                                    onNext: () {
                                      //_assetsAudioPlayer.forward(Duration(seconds: 10));
                                      _assetsAudioPlayer.next(
                                          keepLoopMode:
                                              true /*keepLoopMode: false*/);
                                    },
                                    onPrevious: () {
                                      _assetsAudioPlayer.previous(
                                          /*keepLoopMode: false*/);
                                    },
                                  );
                                });
                          },
                        ),
                        _assetsAudioPlayer.builderRealtimePlayingInfos(
                            builder: (context, RealtimePlayingInfos? infos) {
                          if (infos == null) {
                            return SizedBox();
                          }
                          //print('infos: $infos');
                          return Column(
                            children: [
                              // PositionSeekWidget(
                              //   currentPosition: infos.currentPosition,
                              //   duration: infos.duration,
                              //   seekTo: (to) {
                              //     _assetsAudioPlayer.seek(to);
                              //   },
                              // ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  // NeumorphicButton(
                                  //   onPressed: () {
                                  //     _assetsAudioPlayer
                                  //         .seekBy(Duration(seconds: -10));
                                  //   },
                                  //   child: Text('-10'),
                                  // ),
                                  // SizedBox(
                                  //   width: 12,
                                  // ),
                                  // NeumorphicButton(
                                  //   onPressed: () {
                                  //     _assetsAudioPlayer
                                  //         .seekBy(Duration(seconds: 10));
                                  //   },
                                  //   child: Text('+10'),
                                  // ),
                                ],
                              )
                            ],
                          );
                        }),
                      ],
                    );
                  }),
                  // SizedBox(
                  //   height: 20,
                  // ),
                  // _assetsAudioPlayer.builderCurrent(
                  //     builder: (BuildContext context, Playing? playing) {
                  //   return SongsSelector(
                  //     audios: audios,
                  //     onPlaylistSelected: (myAudios) {
                  //       _assetsAudioPlayer.open(
                  //         Playlist(audios: myAudios),
                  //         showNotification: true,
                  //         headPhoneStrategy:
                  //             HeadPhoneStrategy.pauseOnUnplugPlayOnPlug,
                  //         audioFocusStrategy: AudioFocusStrategy.request(
                  //             resumeAfterInterruption: true),
                  //       );
                  //     },
                  //     onSelected: (myAudio) async {
                  //       try {
                  //         await _assetsAudioPlayer.open(
                  //           myAudio,
                  //           autoStart: true,
                  //           showNotification: true,
                  //           playInBackground: PlayInBackground.enabled,
                  //           audioFocusStrategy: AudioFocusStrategy.request(
                  //               resumeAfterInterruption: true,
                  //               resumeOthersPlayersAfterDone: true),
                  //           headPhoneStrategy: HeadPhoneStrategy.pauseOnUnplug,
                  //           notificationSettings: NotificationSettings(
                  //               //seekBarEnabled: false,
                  //               //stopEnabled: true,
                  //               //customStopAction: (player){
                  //               //  player.stop();
                  //               //}
                  //               //prevEnabled: false,
                  //               //customNextAction: (player) {
                  //               //  print('next');
                  //               //}
                  //               //customStopIcon: AndroidResDrawable(name: 'ic_stop_custom'),
                  //               //customPauseIcon: AndroidResDrawable(name:'ic_pause_custom'),
                  //               //customPlayIcon: AndroidResDrawable(name:'ic_play_custom'),
                  //               ),
                  //         );
                  //       } catch (e) {
                  //         print(e);
                  //       }
                  //     },
                  //     playing: playing,
                  //   );
                  // }),
                  /*
                  PlayerBuilder.volume(
                      player: _assetsAudioPlayer,
                      builder: (context, volume) {
                        return VolumeSelector(
                          volume: volume,
                          onChange: (v) {
                            _assetsAudioPlayer.setVolume(v);
                          },
                        );
                      }),
                   */
                  /*
                  PlayerBuilder.forwardRewindSpeed(
                      player: _assetsAudioPlayer,
                      builder: (context, speed) {
                        return ForwardRewindSelector(
                          speed: speed,
                          onChange: (v) {
                            _assetsAudioPlayer.forwardOrRewind(v);
                          },
                        );
                      }),
                   */
                  /*
                  PlayerBuilder.playSpeed(
                      player: _assetsAudioPlayer,
                      builder: (context, playSpeed) {
                        return PlaySpeedSelector(
                          playSpeed: playSpeed,
                          onChange: (v) {
                            _assetsAudioPlayer.setPlaySpeed(v);
                          },
                        );
                      }),
                   */
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

// converted from a stateless widget into a stateful widget.. - makes the bar change between 'states'
class DrawerApp extends StatefulWidget {
  @override
  _DrawerAppState createState() => _DrawerAppState();
}

class _DrawerAppState extends State<DrawerApp> {
  double sliderValue = 2;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      drawer: DrawerCodeOnly(),
      appBar:
          new AppBar(title: new Text('RADIO'), backgroundColor: Colors.black),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Text(
            'Press to Listen',
            style: TextStyle(color: Colors.black, fontSize: 25),
          ),
          MyApp(),
        ],
      ),
    );
  }
}
kalismeras61 commented 2 years ago

Can you try "flutter clean" and then "flutter pub get"

lyntree commented 2 years ago

Thanks for answering, hasn't worked, same issues :(

lyntree commented 2 years ago

might I add, I also tried 'switching channels and upgrading on each before going back to 'stable' they all had the same issues.

lyntree commented 2 years ago

Hi, Sorry any update on this bug?

kalismeras61 commented 2 years ago

No other one reported that issue. What are you using rxdart on your project ?

lyntree commented 2 years ago

Another Package, I don't remember which one requested that I add it because it wouldn't work without the depenency of RXdart

lyntree commented 2 years ago

Can you confirm, what Gradle version that the Audio Player supports as I've started tinkering around with Gradle and discovered this..

Subproject ':assets_audio_player' has location '/Users/Lyntree/flutter/.pub-cache/hosted/pub.dartlang.org/assets_audio_player-3.0.3+6/android' which is outside of the project root.  
  ** This behaviour has been deprecated and is scheduled to be removed in Gradle 8.0. **  
  Documentation  
  1 usage  
  Unknown:ProjectFactory.java:84  
at org.gradle.api.internal.project.ProjectFactory.nagUserAboutDeprecatedFlatProjectLayout(ProjectFactory.java:84)•••     at org.gradle.api.internal.project.ProjectFactory.nagUserAboutDeprecatedFlatProjectLayout(ProjectFactory.java:84)       •••
    at org.gradle.api.internal.project.ProjectFactory.nagUserAboutDeprecatedFlatProjectLayout(ProjectFactory.java:84)  
    •••

    | Subproject ':assets_audio_player_web' has location '/Users/Lyntree/flutter/.pub-cache/hosted/pub.dartlang.org/assets_audio_player_web-3.0.3+6/android' which is outside of the project root. |     | This behaviour has been deprecated and is scheduled to be removed in Gradle 8.0. |     | Documentation |     | 1 usage

lyntree commented 2 years ago

Right, I'm going to close this as I think it's a problem with Gradle due to accidentally upgrading to Version 7 (req JKD 16) and only having JKD 11 installed.. I have now opened this issue over with Gradle instead.