0.1.1 • Published 2 years ago

expo-music-picker v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Expo Music Picker

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

AndroidDeviceAndroidEmulatoriOSDeviceiOSSimulatorWebExpo 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:

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:

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.

ArtworkImage