cache_audio_player 1.0.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 81

cache_audio_player #

A flutter plugin to play and cache audio files. Works for iOS and Android. The plugin uses 2 channels, one to communicate events from flutter to native, and an event channel to stream the state changes of the native players back to flutter.

Usage #

Import package:cache_audio_player/cache_audio_player.dart and instantiate CacheAudioPlayer;

Example:


final CacheAudioPlayer audioPlayer = CacheAudioPlayer();

//Always register listeners in order to receive updates from event channel.
audioPlayer.registerListeners();

//Event channel callbacks:
audioPlayer.onStateChanged.listen((AudioPlayerState state) {
  setState(() {
      //or do whatever you need to do with the new state
     _state = state;
  });
});

audioPlayer.onPlayerBuffered.listen((double percentageBuffered) {
  setState(() {
     _bufferedPercentage = percentageBuffered;
  });
});

audioPlayer.onTimeElapsed.listen((double timeInSeconds) {
  setState(() {
      _timeInSeconds = timeInSeconds;
   });
  });

audioPlayer.onError.listen((Object error) {
   setState(() {
      _error = error;
  });
});

audioPlayer.loadUrl("your url");
audioPlayer.play();

Getting Started #

This project is a starting point for a Flutter plug-in package, a specialized package that includes platform-specific implementation code for Android and/or iOS.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

1.0.0 #

-Update to register listeners when setting up the player with a new url instead of on initializing the player. -When the event listener is removed don't stop the audio player, leave that to client. -If there is a url with http try to make it https on iOS, and allow it on Android.

0.0.1 #

Creates audio players that handle caching automatically in iOS and Android respectively.

example/lib/main.dart

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

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

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

class _MyAppState extends State<MyApp> {
  final CacheAudioPlayer _audioPlayer = CacheAudioPlayer();
  final String _sampleURL =
      "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";

  StreamSubscription<AudioPlayerState> _stateSubscription;
  StreamSubscription<double> _bufferSubscription;
  StreamSubscription<double> _timeElapsedSubscription;
  StreamSubscription<Object> _errorSubscription;

  AudioPlayerState _state = AudioPlayerState.PAUSED;
  double _bufferedPercentage = 0;
  double _timeInSeconds = 0;
  double _percentageOfTimeElapsed = 0;
  int _totalDuration = 0;
  Object _error;
  bool _isSeekng = false;
  double _valueToSeekTo = 0;

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

    //Always register listeners in order to receive updates from event channel.
    _audioPlayer.registerListeners();
    _stateSubscription =
        _audioPlayer.onStateChanged.listen((AudioPlayerState state) {
      setState(() {
        _state = state;
      });
    });
    _bufferSubscription =
        _audioPlayer.onPlayerBuffered.listen((double percentageBuffered) {
      setState(() {
        _bufferedPercentage = percentageBuffered;
      });
    });
    _timeElapsedSubscription =
        _audioPlayer.onTimeElapsed.listen((double timeInSeconds) {
      setState(() {
        _timeInSeconds = timeInSeconds;
      });
    });
    _errorSubscription = _audioPlayer.onError.listen((Object error) {
      setState(() {
        _error = error;
      });
    });
    _loadPlayerWithSampleUrl();
  }

  _loadPlayerWithSampleUrl() {
    _audioPlayer.loadUrl(_sampleURL);
  }

  @override
  void dispose() {
    super.dispose();
    _stateSubscription.cancel();
    _bufferSubscription.cancel();
    _errorSubscription.cancel();
    _timeElapsedSubscription.cancel();
    _audioPlayer.stop();
    _audioPlayer.unregisterListeners();
  }

  @override
  Widget build(BuildContext context) {
    if (_state == AudioPlayerState.PLAYING || _isSeekng) {
      _updateSliderValue();
    }

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: _playerContainer(),
        ),
      ),
    );
  }

  _playerContainer() {
    return Container(
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              IconButton(
                icon: _icon(),
                onPressed: () {
                  _onPressed();
                },
              ),
              SizedBox(
                width: 20,
              ),
              Slider(
                onChangeEnd: (double value) {
                  _valueToSeekTo = value;
                  _isSeekng = true;
                  _audioPlayer.seek(value).catchError((Object error) {
                    setState(() {
                      _isSeekng = false;
                      _error = error;
                    });
                  });
                },
                onChanged: (value) {},
                value: _percentageOfTimeElapsed,
              ),
            ],
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            children: <Widget>[
              Text("Time: ${formattedTime()}"),
              SizedBox(width: 20,),
              Text("Buffer: $_bufferedPercentage"),
            ],
          ),
          _error == null ? SizedBox() : Text("there was an error $_error"),
        ],
      ),
    );
  }

  String formattedTime() {
    return Duration(seconds: _timeInSeconds.toInt()).toString();
  }

   _updateSliderValue() {
    if (_totalDuration == 0) {
      _audioPlayer.lengthInseconds().then((totalDuration) {
        _totalDuration = totalDuration.toInt();
      }).catchError((error) {
        _error = error;
      });
    } else {
      if (_isSeekng) {
        _isSeekng = false;
        final double value = _valueToSeekTo;
        _valueToSeekTo = 0;
        _percentageOfTimeElapsed = value;
      } else {
        _percentageOfTimeElapsed = min(_timeInSeconds / _totalDuration, 1.0);
      }
    }
  }

  Icon _icon() {
    switch (_state) {
      case AudioPlayerState.PLAYING:
        return Icon(Icons.pause);
      case AudioPlayerState.READYTOPLAY:
      case AudioPlayerState.BUFFERING:
      case AudioPlayerState.PAUSED:
      case AudioPlayerState.FINISHED:
        return Icon(Icons.play_arrow);
      default:
        return Icon(Icons.error);
    }
  }

  _onPressed() {
    switch (_state) {
      case AudioPlayerState.PLAYING:
        return _audioPlayer.stop();
      case AudioPlayerState.READYTOPLAY:
      case AudioPlayerState.BUFFERING:
      case AudioPlayerState.PAUSED:
        return _audioPlayer.play();
      case AudioPlayerState.FINISHED:
        _percentageOfTimeElapsed = 0;
        _timeInSeconds = 0;
        return _audioPlayer.play();
      default:
        {}
    }
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  cache_audio_player: ^1.0.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:cache_audio_player/cache_audio_player.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
65
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
81
Learn more about scoring.

We analyzed this package on Jul 2, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because of import path [package:cache_audio_player/cache_audio_player.dart] that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because of import path [package:cache_audio_player/cache_audio_player.dart] that declares support for platforms: android, ios

Package does not support Flutter platform web

Because of import path [package:cache_audio_player/cache_audio_player.dart] that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because of import path [package:cache_audio_player/cache_audio_player.dart] that declares support for platforms: android, ios

Package not compatible with SDK dart

because of import path [cache_audio_player] that is in a package requiring null.

Maintenance suggestions

The description is too long. (-10 points)

Search engines display only the first part of the description. Try to keep the value of the description field in your package's pubspec.yaml file between 60 and 180 characters.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test