Flutter Plugin Used to Query Audios/songs infos From Device Storage

Platforms:

MethodsAndroidIOSWeb
querySongs✔️✔️✔️
queryAlbums✔️✔️✔️
queryArtists✔️✔️✔️
queryPlaylists✔️✔️
queryGenres✔️✔️✔️
queryAudiosFrom✔️✔️✔️
queryWithFilters✔️✔️✔️
queryArtwork✔️✔️✔️
createPlaylist✔️✔️
removePlaylist✔️
addToPlaylist✔️✔️
removeFromPlaylist✔️
renamePlaylist✔️
moveItemTo✔️
checkAndRequest✔️✔️
permissionsRequest✔️✔️
permissionsStatus✔️✔️
queryDeviceInfo✔️✔️✔️
scanMedia✔️

✔️ -> Supported
❌ -> Not Supported
 

See all platforms methods support

Installation:

Add the following code to your pubspec.yaml:

dependencies:
  on_audio_query: ^2.9.0

Request Permission:

Android:

To use this plugin add the following code to your AndroidManifest.xml

<manifest>
  
  <!-- Android 12 or below  -->
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

  <!-- Android 13 or greater  -->
  <uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
  <uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
  <uses-permission android:name="android.permission.READ_MEDIA_AUDIO"/>

</manifest>

IOS:

To use this plugin add the following code to your Info.plist

<dict>

	<key>NSAppleMusicUsageDescription</key>
	<string>$(PROJECT_NAME) requires access to media library</string>

</dict>

Some Features:

  • Optional and Built-in storage READ and WRITE permission request
  • Get all audios/songs.
  • Get all albums and album-specific audios.
  • Get all artists and artist-specific audios.
  • Get all playlists and playlists-specific audios.
  • Get all genres and genres-specific audios.
  • Get all query methods with specific keys [Search].
  • Create/Delete/Rename playlists.
  • Add/Remove/Move specific audios to playlists.
  • Specific sort types for all query methods.

Overview:

All types of methods on this plugin:

Artwork Widget

  Widget someOtherName() async {
    return QueryArtworkWidget(
      id: <audioId>,
      type: ArtworkType.AUDIO,
    );
  }

See more: QueryArtworkWidget

Examples:

OnAudioQuery

final OnAudioQuery _audioQuery = OnAudioQuery();

Query methods:

  • queryAudios();
  • queryAlbums();
  • queryArtists();
  • queryPlaylists();
  • queryGenres().
  someName() async {
    // Query Audios
    List<AudioModel> audios = await _audioQuery.queryAudios();

    // Query Albums
    List<AlbumModel> albums = await _audioQuery.queryAlbums();
  }

scanMedia

You'll use this method when updating a media from storage. This method will update the media 'state' and Android MediaStore will be able to know this 'state'.

  someName() async {
    OnAudioQuery _audioQuery = OnAudioQuery();
    File file = File('path');
    try {
      if (file.existsSync()) {
        file.deleteSync();
        _audioQuery.scanMedia(file.path); // Scan the media 'path'
      }
    } catch (e) {
      debugPrint('$e');
    }
  }

queryArtwork

  someName() async {
    // DEFAULT: ArtworkFormat.JPEG, 200 and false
    Uint8List something = await _audioQuery.queryArtwork(
        <audioId>,
        ArtworkType.AUDIO,
        ...,
      );
  }

Or you can use a basic and custom Widget. See example QueryArtworkWidget

Gif Examples:

SongsAlbumsPlaylistsArtists

LICENSE:

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add on_audio_query

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  on_audio_query: ^2.9.0

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

Import it

Now in your Dart code, you can use:

import 'package:on_audio_query/on_audio_query.dart';

example/lib/main.dart

/*
=============
Author: Lucas Josino
Github: https://github.com/LucJosin
Website: https://www.lucasjosino.com/
=============
Plugin/Id: on_audio_query#0
Homepage: https://github.com/LucJosin/on_audio_query
Pub: https://pub.dev/packages/on_audio_query
License: https://github.com/LucJosin/on_audio_query/blob/main/on_audio_query/LICENSE
Copyright: © 2021, Lucas Josino. All rights reserved.
=============
*/

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

void main() {
  runApp(
    const MaterialApp(
      home: Songs(),
    ),
  );
}

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

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

class _SongsState extends State<Songs> {
  // Main method.
  final OnAudioQuery _audioQuery = OnAudioQuery();

  // Indicate if application has permission to the library.
  bool _hasPermission = false;

  @override
  void initState() {
    super.initState();
    // (Optinal) Set logging level. By default will be set to 'WARN'.
    //
    // Log will appear on:
    //  * XCode: Debug Console
    //  * VsCode: Debug Console
    //  * Android Studio: Debug and Logcat Console
    LogConfig logConfig = LogConfig(logType: LogType.DEBUG);
    _audioQuery.setLogConfig(logConfig);

    // Check and request for permission.
    checkAndRequestPermissions();
  }

  checkAndRequestPermissions({bool retry = false}) async {
    // The param 'retryRequest' is false, by default.
    _hasPermission = await _audioQuery.checkAndRequest(
      retryRequest: retry,
    );

    // Only call update the UI if application has all required permissions.
    _hasPermission ? setState(() {}) : null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("OnAudioQueryExample"),
        elevation: 2,
      ),
      body: Center(
        child: !_hasPermission
            ? noAccessToLibraryWidget()
            : FutureBuilder<List<SongModel>>(
                // Default values:
                future: _audioQuery.querySongs(
                  sortType: null,
                  orderType: OrderType.ASC_OR_SMALLER,
                  uriType: UriType.EXTERNAL,
                  ignoreCase: true,
                ),
                builder: (context, item) {
                  // Display error, if any.
                  if (item.hasError) {
                    return Text(item.error.toString());
                  }

                  // Waiting content.
                  if (item.data == null) {
                    return const CircularProgressIndicator();
                  }

                  // 'Library' is empty.
                  if (item.data!.isEmpty) return const Text("Nothing found!");

                  // You can use [item.data!] direct or you can create a:
                  // List<SongModel> songs = item.data!;
                  return ListView.builder(
                    itemCount: item.data!.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text(item.data![index].title),
                        subtitle: Text(item.data![index].artist ?? "No Artist"),
                        trailing: const Icon(Icons.arrow_forward_rounded),
                        // This Widget will query/load image.
                        // You can use/create your own widget/method using [queryArtwork].
                        leading: QueryArtworkWidget(
                          controller: _audioQuery,
                          id: item.data![index].id,
                          type: ArtworkType.AUDIO,
                        ),
                      );
                    },
                  );
                },
              ),
      ),
    );
  }

  Widget noAccessToLibraryWidget() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.redAccent.withOpacity(0.5),
      ),
      padding: const EdgeInsets.all(20),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text("Application doesn't have access to the library"),
          const SizedBox(height: 10),
          ElevatedButton(
            onPressed: () => checkAndRequestPermissions(retry: true),
            child: const Text("Allow"),
          ),
        ],
      ),
    );
  }
}

Download details:

Author: lucasjosino.com

Source: https://github.com/LucJosin/on_audio_query/tree/main/packages/on_audio_query

#flutter #dart #sql #video #mobile-apps 

Flutter Plugin Used to Query Audios/songs infos From Device Storage
2.85 GEEK