A music picker library for React Native. Provides access to the system's UI for selecting songs from the phone's music library.

Overview

Expo Music Picker

expo-image-picker demo

A music picker library for React Native. Provides access to the system's UI for selecting songs from the phone's music library.

Supported platforms

Android
Device
Android
Emulator
iOS
Device
iOS
Simulator
Web Expo Go

This library requires Expo SDK 45 or newer

Installation

npx expo install expo-music-picker

Once the library is installed, create a new Development Build.

If you're installing this in a bare React Native app, you will need to have the expo package installed and configured.

Configuration in app.json / app.config.js

Add expo-music-picker to the plugins array of your app.json or app.config.js and then create a new Development Build to apply the changes.

{
  "expo": {
    "plugins": [
      "expo-music-picker",
      { "musicLibraryPermission": "The app accesses your music to play it" }
    ]
  }
}

The config plugin has the following options:

Name Type Explanation Required Default Value
musicLibraryPermission string 🍏 iOS only A string to set the NSAppleMusicUsageDescription permission message. "Allow $(PRODUCT_NAME) to access your music library"

Configuration for iOS 🍏

This is only required for usage in bare React Native apps.

Add NSAppleMusicUsageDescription key to your Info.plist:

<key>NSAppleMusicUsageDescription</key>
<string>Give $(PRODUCT_NAME) permission to access your music library</string>

Run npx pod-install after installing the npm package.

Configuration for Android 🤖

This is only required for usage in bare React Native apps.

This package automatically adds the READ_EXTERNAL_STORAGE permission. It is used when picking music from the phone's library.

<!-- Added permissions -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Usage

import { useState } from "react";
import { Image, Text, View, Button } from "react-native";

import * as MusicPicker from "expo-music-picker";

export default function App() {
  const [item, setItem] = useState<MusicPicker.MusicItem | null>();

  const pickMediaAsync = async () => {
    try {
      // Request permissions
      const permissionResult = await MusicPicker.requestPermissionsAsync();
      if (!permissionResult.granted) {
        console.warn("No permission");
        return;
      }

      // Open the music picker
      const result = await MusicPicker.openMusicLibraryAsync({
        allowMultipleSelection: true,
        includeArtworkImage: true,
      });

      // Process the result
      console.log(result);
      if (!result.cancelled) {
        const [firstItem] = result.items;
        setItem(firstItem ?? null);
      }
    } catch (e) {
      console.warn("Exception occurred when picking music:", e);
    }
  };

  const artworkData = item?.artworkImage?.base64Data;

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Button title="Open music library" onPress={pickMediaAsync} />
      <Text>
        {item ? `Song: ${item.artist} - ${item.title}` : "No song selected"}
      </Text>
      {artworkData && (
        <Image
          source={{ uri: `data:image/jpeg;base64,${artworkData}` }}
          style={{ width: 200, height: 200 }}
          resizeMode="contain"
        />
      )}
    </View>
  );
}

API

import * as MusicPicker from `expo-music-picker`;

requestPermissionsAsync(): Promise<PermissionResponse>

Asks the user to grant permissions for accessing user's music library.

  • 🍏 On iOS this is required to open the picker.
  • 🤖 On Android this is not required, but recommended to get the most accurate results. Only basic metadata will be retrieved without that permission.
  • 🌐 On Web this does nothing - the permission is always granted.

Returns: A promise that fulfills with Expo standard permission response object.

getPermissionsAsync(): Promise<PermissionResponse>

Checks user's permissions for accessing music library.

On Web, this does nothing - the permission is always granted.

Returns: A promise that fulfills with Expo standard permission response object.

openMusicLibraryAsync(options?: MusicPickerOptions): Promise<PickerResult>

Display the system UI for choosing a song / audio file from the phone's library.

On Web: The system UI can only be shown after user activation (e.g. a button press), otherwise the browser will block the request without a warning.

Arguments:

Returns: An object of type PickerResult.


MusicPickerOptions

Options for the picker:

Name Type Explanation Required Default Value
allowMultipleSelection boolean Whether or not to allow selecting multiple media files at once. false
includeArtworkImage boolean Whether to also include the artwork image dimensions and its data in Base64 format. false
showCloudItems boolean 🍏 iOS only When set to true, the picker shows available iCloud Music Library items, including purchased items, imported content, and Apple Music subscription content. When set to false, the picker only shows content downloaded to the device. true
userPrompt string | undefined 🍏 iOS only A prompt, for the user, that appears above the navigation bar buttons on the picker screen. undefined

PickerResult

A picking result resolved by openMusicLibraryAsync.

type PickerResult =
  | { cancelled: true }
  | { cancelled: false; items: MusicItem[] };

When the cancelled property is false, the picked music items are available under the items property.

MusicItem

Represents a single picked music item.

Name Type Description
id number Unique asset ID. On Android, this value can be used to access the asset with expo-media-library. If the ID cannot be obtained, the value is -1.
uri string URI of the asset. It can be used to play selected media with expo-av.
title string? The title or name of the music item.
artist string? The performing artist the music item.
album string? The title of an album.
durationSeconds number The duration of the music item in seconds. Returns -1 if unavailable.
track number? The track number of the media item, for a media item that is part of an album.
year number? 🤖 🌐 Android & Web only. Year of the song.
fileName string? 🤖 Android only. The filename of the media. Example: toto_africa.mp3
artworkImage ArtworkImage? When options.includeArtworkImage is true and the music item has attached artwork image, it can be accessed by this property. See ArtworkImage type below.

ArtworkImage

Name Type Description
width number Original width of the artwork image.
height number Original height of the artwork image.
base64Data string Base64-encoded image data. Does NOT include the data:...;base64, prefix.
You might also like...
Library to read incoming SMS in Android for Expo (React Native)

react-native-expo-read-sms Maintainers maniac-tech Active maintainer Installation Install this in your managed Expo project by running this command: $

Initiate immediate phone call for React Native on iOS and Android.

react-native-immediate-call-library Initiate immediate phone call for React Native on iOS and Android. Getting started Using npm: npm install react-na

A react native interface for integrating payments using PayPal

react-native-paypal Getting started Installation npm install react-native-paypal Android Specific Add this to your build.gradle maven { url "https:

A 2020s compatible React Native keyboard avoiding view for Android and iOS that just works.

react-native-keyboard-shift Example Snack coming soon Until then: Clone this repo: git clone https://github.com/FullStackCraft/react-native-keyboard-s

Make SIP calls from react-native using Linphone SDK

react-native-sip Make SIP calls from react-native using Linphone SDK Installation npm install react-native-sip Usage import { multiply } from "react-n

A demo for Android font typeface support in React Native!
A demo for Android font typeface support in React Native!

A Step-by-step Guide to a Consistent Multi-Platform Font Typeface Experience in React Native Goal Be able to use font typeface modifiers such as fontW

A framework for building native applications using React

React Native Learn once, write anywhere: Build mobile apps with React. Getting Started · Learn the Basics · Showcase · Contribute · Community · Suppor

Wrapper for Kustomer SDK v2.0 for react native
Wrapper for Kustomer SDK v2.0 for react native

This is a wrapper for Kustomer v2 Sdk for react native. This implements the kust

🚀 React Native Segmented Control, Pure Javascript for iOS and Android
🚀 React Native Segmented Control, Pure Javascript for iOS and Android

Installation Add the dependency: npm i react-native-segmented-control-2 Peer Dependencies Zero Dependency 🥳 Usage Import import SegmentedControl from

Comments
  • Crash on Android 12 after pick music track

    Crash on Android 12 after pick music track

    Hi,

    Nice idea - looking forward to getting it working on Android ! Have got the bluetooth side of things working on some 'Arduino-like' hardware, but having problems with the music picker: the application crashes with the below error message. If I select a track with the native music picker it will start playing, but as soon as I click on 'Done' it crashes. Note that it doesn't get as far as the check to see if the result has been cancelled: I put in a console.log just after the return from 'openMusicLibraryAsync' which doesn't get called. I also put in a call to 'requestPermissionsAsync' which correctly asked me for permissions the first time.

    Crash trace: Your app just crashed. See the error below.

    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2317, result=-1, data=Intent { dat=content://media/external/audio/media/14 typ=audio/mpeg flg=0x1 }} to activity {com.barthap.expomegademo/com.barthap.expomegademo.MainActivity}: java.lang.IllegalArgumentException: Invalid column last_modified
    at android.app.ActivityThread.deliverResults(ActivityThread.java:5946)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:5985)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
    at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2443)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8751)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
    at Caused By android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:172)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:142)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:481)
    at android.content.ContentResolver.query(ContentResolver.java:1226)
    at android.content.ContentResolver.query(ContentResolver.java:1158)
    at android.content.ContentResolver.query(ContentResolver.java:1114)
    at expo.community.modules.musicpicker.MusicMetadataResolver.getDirectUriInfo(MusicMetadataResolver.kt:162)
    at expo.community.modules.musicpicker.MusicMetadataResolver.getMusicMetadata(MusicMetadataResolver.kt:46)
    at expo.community.modules.musicpicker.MusicPickerModule.getMusicMetadata(MusicPickerModule.kt:92)
    at expo.community.modules.musicpicker.MusicPickerModule.processPickerResult(MusicPickerModule.kt:109)
    at expo.community.modules.musicpicker.MusicPickerModule.access$processPickerResult(MusicPickerModule.kt:37)
    at expo.community.modules.musicpicker.MusicPickerModule$definition$lambda-5$$inlined$OnActivityResult$1.invoke(ModuleDefinitionBuilder.kt:604)
    at expo.community.modules.musicpicker.MusicPickerModule$definition$lambda-5$$inlined$OnActivityResult$1.invoke(ModuleDefinitionBuilder.kt:597)
    at expo.modules.kotlin.events.EventListenerWithSenderAndPayload.call(EventListener.kt:37)
    at expo.modules.kotlin.ModuleHolder.post(ModuleHolder.kt:40)
    at expo.modules.kotlin.ModuleRegistry.post(ModuleRegistry.kt:67)
    at expo.modules.kotlin.AppContext.onActivityResult(AppContext.kt:167)
    at expo.modules.kotlin.ReactLifecycleDelegate.onActivityResult(ReactLifecycleDelegate.kt:33)
    at com.facebook.react.bridge.ReactContext.onActivityResult(ReactContext.java:328)
    at com.facebook.react.ReactInstanceManager.onActivityResult(ReactInstanceManager.java:828)
    at com.facebook.react.ReactDelegate.onActivityResult(ReactDelegate.java:90)
    at com.facebook.react.ReactActivityDelegate.onActivityResult(ReactActivityDelegate.java:113)
    at expo.modules.ReactActivityDelegateWrapper.onActivityResult(ReactActivityDelegateWrapper.kt:145)
    at com.facebook.react.ReactActivity.onActivityResult(ReactActivity.java:70)
    at android.app.Activity.dispatchActivityResult(Activity.java:8659)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:5939)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:5985)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
    at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2443)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8751)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
    

    Any ideas ?

    Thanks,

    Nic

    opened by nicredshaw 3
Releases(v0.1.1)
Owner
Bartłomiej Klocek
Bartłomiej Klocek
React-native-user-interface - Change React Native userinterface at runtime

react-native-user-interface change RN userinterface at runtime. Installation npm

Ahmed Eid 0 Jan 11, 2022
NativeScript empowers you to access native platform APIs from JavaScript directly. Angular, Capacitor, Ionic, React, Svelte, Vue and you name it compatible.

NativeScript empowers you to access native APIs from JavaScript directly. The framework currently provides iOS and Android runtimes for rich mobile de

NativeScript 22k Dec 31, 2022
Matomo wrapper for React-Native. Supports Android and iOS. Fixed issues for native platforms build that are present in the official package.

@mccsoft/react-native-matomo Matomo wrapper for React-Native. Supports Android and iOS. Fixed issues for native platforms build that are present in th

MCC Soft 4 Dec 29, 2022
Project for academic course "Telemedicine systems" held on Warsaw University of Technology.

Electronic-Fever-Cards Project for academic course "Telemedicine systems" held on Warsaw University of Technology. This application has two user profi

null 0 Dec 28, 2021
An offline assistant for Android phones

The Sapphire Assistant Framework If you are looking for an Android assistant that is easy to use, flexible, and respects your privacy then look no fur

Christopher Carroll 286 Dec 28, 2022
Ankiconnect Android allows you to utilize the standard Anki mining workflow on Android devices like phones and eReaders

Ankiconnect Android Ankiconnect Android allows you to utilize the standard Anki mining workflow on Android devices like phones and eReaders. Create An

Kamron Bhavnagri 29 Dec 28, 2022
Demo of Downloading Songs/Images through Android Download Manager using RxJava2

Downloader Demo using RxJava Overview This project is for downloading items(songs, images etc) in Android using RxJava2. There are, however 2 conditio

Anshul Jain 168 Nov 25, 2022
NetGuard provides simple and advanced ways to block access to the internet

NetGuard NetGuard provides simple and advanced ways to block access to the internet - no root required. Applications and addresses can individually be

Marcel Bokhorst 598 Dec 31, 2022
Picker-kt - Media picker library powered by Jetpack Compose

ANDROID LIBRARY PickerKT A media picker library for Android apps powered by Jetp

Tanawin Wichit 20 Jan 2, 2023
Simple library to decompress files .zip, .rar, .cbz, .cbr in React Native.

Uncompress React Native Simple library to decompress files .zip, .rar, .cbz and .cbr in React Native. Installation yarn add uncompress-react-native o

Adriano Souza Costa 40 Nov 24, 2022