need_help_1234
need_help_1234

Reputation: 43

Background music in Flutter does not work

I'm trying to add background music to my app. if i start my app the music starts rightly, but if i press a button which should have no impact to the music, the music starts from new. i code in Flutter.Here is my code i cutted the unimportant things away.

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';


class _MyHomepageState extends State<MyHomepage> {
  AudioPlayer player = AudioPlayer();
  AudioCache cache = new AudioCache();
  bool isPlaying = false;

  Future<bool> _willPopCallback() async {
    if (isPlaying == false) {
      setState(() {
        isPlaying = true;
      });
      player.stop();
    }
    return true;
  }

  openingActions() async {
    player = await cache.loop('audio/test.mp3');
  }

 
  @override
  Widget build(BuildContext context) {
    openingActions();
    return WillPopScope(
        onWillPop: () => _willPopCallback(),
        child: Scaffold(
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/background.jpg'),
                fit: BoxFit.cover,
              ),
            ),
    ...
    ...
    ...
raisedbutton(
....
)


Upvotes: 0

Views: 609

Answers (1)

chunhunghan
chunhunghan

Reputation: 54407

You can copy paste run full code below
You can move openingActions(); from build to initState
And rebuild will not call openingActions(); again

@override
  void initState() {
    openingActions();
    super.initState();
  }

@override
  Widget build(BuildContext context) {
    //openingActions(); //delete this line and move to initState

full code

import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  AudioPlayer player = AudioPlayer();
  AudioCache cache = new AudioCache();
  bool isPlaying = false;

  Future<bool> _willPopCallback() async {
    if (isPlaying == false) {
      setState(() {
        isPlaying = true;
      });
      player.stop();
    }
    return true;
  }

  openingActions() async {
    player = await cache.loop('audio/test.mp3');
  }

  int _counter = 0;

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

  @override
  void initState() {
    openingActions();
    super.initState();
  }

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

Upvotes: 0

Related Questions