audio_service 0.0.2 copy "audio_service: ^0.0.2" to clipboard
audio_service: ^0.0.2 copied to clipboard

outdated

Flutter plugin to play audio in the background while the screen is off.

example/lib/main.dart

import 'dart:io';

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

import 'package:audio_service/audio_service.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:soundpool/soundpool.dart';

void main() => runApp(new MyApp());

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

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  PlaybackState state;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    connect();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        connect();
        break;
      case AppLifecycleState.paused:
        AudioService.disconnect();
        break;
      default:
        break;
    }
  }

  void connect() {
    AudioService.connect(
      onPlaybackStateChanged: (state, position, speed, updateTime) {
        setState(() {
          this.state = state;
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Audio Service Demo'),
        ),
        body: new Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              state == PlaybackState.playing ? pauseButton() : playButton(),
              stopButton(),
            ],
          ),
        ),
      ),
    );
  }

  IconButton playButton() => IconButton(
        icon: Icon(Icons.play_arrow),
        iconSize: 64.0,
        onPressed: () {
          if (state == PlaybackState.paused) {
            AudioService.resume();
          } else {
            AudioService.start(
              backgroundTask: _backgroundCallback,
              notificationChannelName: 'Audio Service Demo',
              androidNotificationIcon: 'mipmap/ic_launcher',
            );
          }
        },
      );

  IconButton pauseButton() => IconButton(
        icon: Icon(Icons.pause),
        iconSize: 64.0,
        onPressed: AudioService.pause,
      );

  IconButton stopButton() => IconButton(
        icon: Icon(Icons.stop),
        iconSize: 64.0,
        onPressed: AudioService.stop,
      );
}

void _backgroundCallback() async {
  ClickPlayer player = ClickPlayer();
  AudioServiceBackground.run(
    doTask: player.run,
    onPause: player.pause,
    onStop: player.stop,
  );
}

class ClickPlayer {
  bool running = false;
  Soundpool soundpool = Soundpool(streamType: StreamType.music);

  Future<void> run() async {
    running = true;
    soundpool = Soundpool(streamType: StreamType.music);
    String clickName = 'click.wav';
    String path = p.join((await getTemporaryDirectory()).path, clickName);
    final file = new File(path);
    await file.writeAsBytes(
        (await rootBundle.load('assets/$clickName')).buffer.asUint8List());

    int clickSoundId = await soundpool.loadUri('file://$path');
    AudioServiceBackground.setState(
      controls: [
        MediaControl(
            androidIcon: 'drawable/ic_action_stop',
            label: 'Stop',
            action: MediaAction.stop),
        MediaControl(
            androidIcon: 'drawable/ic_action_pause',
            label: 'Pause',
            action: MediaAction.pause),
      ],
      state: PlaybackState.playing,
    );
    for (int i = 1; running && i <= 100; i++) {
      await soundpool.play(clickSoundId);
      await Future.delayed(Duration(milliseconds: 1000));
    }
  }

  void stop() {
    AudioServiceBackground.setState(
      controls: [],
      state: PlaybackState.stopped,
    );
    running = false;
  }

  void pause() {
    AudioServiceBackground.setState(
      controls: [
        MediaControl(
            androidIcon: 'drawable/ic_action_stop',
            label: 'Stop',
            action: MediaAction.stop),
        MediaControl(
            androidIcon: 'drawable/ic_action_play_arrow',
            label: 'Play',
            action: MediaAction.play),
      ],
      state: PlaybackState.paused,
    );
    running = false;
  }
}
1117
likes
0
pub points
98%
popularity

Publisher

verified publisherryanheise.com

Flutter plugin to play audio in the background while the screen is off.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

Dependencies

flutter

More

Packages that depend on audio_service