0

I am new to flutter and the just_audio package, and am simply trying to reproduce the code on their website.

My Goal - I would like to use this simple AudioPlayer() constructor to get some audio playing on my app with a few lines of code.

Minimal Code Example - After adding the following code to the flutter create standard app...

in main.dart

import 'package:just_audio/just_audio.dart';

final player = AudioPlayer();                
final duration = await player.setUrl(           
    'https://example.com/bar.mp3');                    
player.play(); 

and in pubspec.yaml just_audio: ^0.9.28

I get the following error

Error: Can't use 'player' because it is declared more than once.

The app runs when I take these lines out, but I'm not sure why they don't work because they are copy-pasted from the docs.

I searched their github issues and didn't find anything about this, and also didn't find anything already on Stack Overflow.

To Reproduce

  1. Terminal: flutter create audio_app
  2. Terminal: flutter pub add just_audio
  3. Copy paste code from their website into main.dart -- my code above.

My Environment

  • Mac OS Big Sur
  • Flutter 3.0.5 • channel stable • https://github.com/flutter/flutter.git
  • Framework • revision f1875d570e (6 weeks ago) • 2022-07-13 11:24:16 -0700
  • Engine • revision e85ea0e79c
  • Tools • Dart 2.17.6 • DevTools 2.12.2
  • just_audio: ^0.9.28
  • Testing simulation on Simulator v13.2

Any help understanding what is going on and how to fix it is appreciated. Let me know if you need me to attach more code.

Full main.dart file as requested

import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';

void main() {
  runApp(const MyApp());
}

final player = AudioPlayer();                   // Create a player
final duration = await player.setUrl(           // Load a URL
    'http://music.thomasmeli.com/wp-content/uploads/2022/05/Thomas-Meli-Binary-Star-Sample.mp3');                 // Schemes: (https: | file: | asset: )
player.play(); 


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

1 Answers1

0

player.setUrl is a future method, while you are using await this part needed to be wrapped in async function. Or README the just provided the necessary part to play, You can follow example for better understanding about widget

If you can do on button presses, it will be

on initState

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    _playSound();
  }

  _playSound() async {
    final player = AudioPlayer(); // Create a player
    final url =
        'http://music.thomasmeli.com/wp-content/uploads/2022/05/Thomas-Meli-Binary-Star-Sample.mp3';
    await player.setAudioSource(AudioSource.uri(Uri.parse(url)));
    await player.play();
  }

Try this widget,


class GA extends StatefulWidget {
  const GA({Key? key}) : super(key: key);

  @override
  State<GA> createState() => _GAState();
}

class _GAState extends State<GA> {
  @override
  void initState() {
    super.initState();
    _playSound();
  }

  _playSound() async {
    final player = AudioPlayer(); // Create a player
    final url =
        'http://music.thomasmeli.com/wp-content/uploads/2022/05/Thomas-Meli-Binary-Star-Sample.mp3';
    await player.setAudioSource(AudioSource.uri(Uri.parse(url)));
    await player.play();
  }

  @override
  Widget build(BuildContext context) {
    int selected = 1;

    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // showContentDialog(context);
          _playSound();
        },
      ),
    );
  }
}

You can explore more about how async-await works

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Thank you for your quick response. Unfortunately, I get the following errors when adding the above code in the main() function. ```[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: Binding has not yet been initialized. The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.``` And ```BindingBase.checkInstance. (package:flutter/src/<…>``` and 2 more, but it is too long for a comment, let me know if you want me to attach it to the main thread. – Thomas Meli Aug 25 '22 at 16:59
  • include `void main() async{WidgetsFlutterBinding.ensureInitialized();...` I will suggest using last two method – Md. Yeasin Sheikh Aug 25 '22 at 17:00
  • OK, we're getting closer. The void main thing still created errors, so I tried your initState code instead. Now I'm getting this error ```unhandled Exception: (-11800) The operation could not be completed #0 AudioPlayer._load (package:just_audio/just_audio.dart:840:9) #1 AudioPlayer._setPlatformActive.setPlatform (package:just_audio/just_audio.dart:1421:28) ``` – Thomas Meli Aug 25 '22 at 17:19
  • Looking at [but doesn't look solved]: https://stackoverflow.com/questions/69786257/just-audio-not-working-on-ios-flutter-unhandled-exception-11800-the-operatio – Thomas Meli Aug 25 '22 at 17:25
  • Try current one – Md. Yeasin Sheikh Aug 25 '22 at 17:29
  • Same error: ui_dart_state.cc(198)] Unhandled Exception: (-11800) – Thomas Meli Aug 25 '22 at 17:49
  • remove others `player`, save the file, and build again – Md. Yeasin Sheikh Aug 25 '22 at 17:52
  • As per the documentation - I tried adding ```NSAppTransportSecurity NSAllowsArbitraryLoads``` To the plist file, and that didn't do anything. – Thomas Meli Aug 25 '22 at 17:57
  • I'm not sure what you mean by "remove others player." Would you clarify? Also, should we move this to chat? – Thomas Meli Aug 25 '22 at 18:01
  • use `home:GA()` widget , – Md. Yeasin Sheikh Aug 25 '22 at 18:06
  • I tried looking that up and I'm not sure what that is referring to. Would you be more specific? Also, did you get this working on your machine? – Thomas Meli Aug 25 '22 at 19:40
  • create a new project and try the widget. also you can try `flutter clean` and `flutter upgrade` – Md. Yeasin Sheikh Aug 26 '22 at 05:49
  • Any way you could include your entire working main.dart file? I'm confused as to what you are referring to above and haven't gotten it to work yet. – Thomas Meli Aug 26 '22 at 18:26