### Start Metro Server for Example App Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Starts the Metro bundler to serve the example application. This is necessary to run the example app on a device or emulator. ```sh yarn example start ``` -------------------------------- ### Fetch and Display All Tracks Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/getting-started.md Retrieves all available music tracks from the device and iterates through them, logging the title, artist, duration, and file URL for each track. Includes error handling for the asynchronous operation. ```javascript const loadTracks = async () => { try { const result = await getTracksAsync(); result.items.forEach(track => { console.log(`${track.title} by ${track.artist}`); console.log(`Duration: ${Math.floor(track.duration / 60)}:${track.duration % 60}`); console.log(`File: ${track.url}`); }); } catch (error) { console.error('Failed to load tracks:', error); } }; ``` -------------------------------- ### Install iOS CocoaPods Dependencies Source: https://github.com/nodefinity/react-native-music-library/blob/main/example/README.md Installs necessary CocoaPods dependencies for the iOS build. This is required before running the iOS app, especially after cloning the project or updating native dependencies. Uses Ruby's bundle command. ```shell # Install CocoaPods itself (first time) bundle install # Install project dependencies bundle exec pod install ``` -------------------------------- ### Import Core Functions from React Native Music Library Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/getting-started.md Imports essential functions for interacting with the music library, including fetching tracks, albums, and artists, as well as getting specific track metadata. ```javascript import { getTracksAsync, getAlbumsAsync, getArtistsAsync, getTrackMetadataAsync } from '@nodefinity/react-native-music-library'; ``` -------------------------------- ### Install React Native Music Library Source: https://github.com/nodefinity/react-native-music-library/blob/main/README.md Instructions for installing the library using npm or yarn. ```bash npm install @nodefinity/react-native-music-library # or yarn add @nodefinity/react-native-music-library ``` -------------------------------- ### Start Metro Bundler in React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/example/README.md Starts the Metro JavaScript bundler, which is essential for serving your React Native application to the emulator/device. This command can be run using either npm or Yarn. ```shell # Using npm npm start # OR using Yarn yarn start ``` -------------------------------- ### Fetch and Display Albums Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/getting-started.md Fetches music albums, optionally sorted by title in ascending order and limited to the first 50 results. It then logs the title, artist, and track count for each album. Error handling is included. ```javascript const loadAlbums = async () => { try { const result = await getAlbumsAsync({ sortBy: ['title', true], // Sort by title ascending first: 50 }); result.items.forEach(album => { console.log(`${album.title} by ${album.artist}`); console.log(`Tracks: ${album.trackCount}`); }); } catch (error) { console.error('Failed to load albums:', error); } }; ``` -------------------------------- ### Fetch and Display Artists Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/getting-started.md Retrieves a list of artists from the music library, sorted by their name. It then logs the artist's title, the number of albums they have, and the total number of tracks. Includes error handling. ```javascript const loadArtists = async () => { try { const result = await getArtistsAsync({ sortBy: 'title' // Sort by name }); result.items.forEach(artist => { console.log(`${artist.title}`); console.log(`Albums: ${artist.albumCount}, Tracks: ${artist.trackCount}`); }); } catch (error) { console.error('Failed to load artists:', error); } }; ``` -------------------------------- ### Run iOS App in React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/example/README.md Builds and runs the React Native application on an iOS simulator or device. This command is executed after ensuring all CocoaPods dependencies are installed. Supports both npm and Yarn. ```shell # Using npm npm run ios # OR using Yarn yarn ios ``` -------------------------------- ### iOS Info.plist Configuration for Music Access Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/getting-started.md Adds the necessary key to the `Info.plist` file for iOS applications to request user permission for accessing their music library. This string will be displayed to the user when the permission prompt appears. ```xml NSAppleMusicUsageDescription This app needs access to your music library to play songs ``` -------------------------------- ### Run Example App on iOS Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Builds and runs the example application on an iOS device or simulator. Ensure you have an iOS development environment set up (Xcode). ```sh yarn example ios ``` -------------------------------- ### Android Permissions for Music Library Access Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/getting-started.md Configures necessary permissions in `AndroidManifest.xml` for Android to access audio media. It includes granular permissions for Android 13+ and traditional storage permissions for older versions. ```xml ``` -------------------------------- ### Run Example App on Android Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Builds and runs the example application on an Android device or emulator. Ensure you have an Android development environment set up. ```sh yarn example android ``` -------------------------------- ### Run Android App in React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/example/README.md Builds and runs the React Native application on an Android device or emulator. This command should be executed in a separate terminal after Metro is running. Supports both npm and Yarn. ```shell # Using npm npm run android # OR using Yarn yarn android ``` -------------------------------- ### Request Music Library Permission in React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/getting-started.md Demonstrates how to request audio media permissions at runtime in a React Native application using the `react-native-permissions` library. It checks the result and logs whether the permission was granted or denied. ```javascript import { request, PERMISSIONS, RESULTS } from 'react-native-permissions'; const requestMusicPermission = async () => { const result = await request(PERMISSIONS.ANDROID.READ_MEDIA_AUDIO); if (result === RESULTS.GRANTED) { console.log('Music permission granted'); } else { console.log('Music permission denied'); } }; ``` -------------------------------- ### Install Project Dependencies with Yarn Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Installs all necessary dependencies for the monorepo project using Yarn workspaces. This command should be run in the root directory. Note that npm is not supported for development due to Yarn workspaces. ```sh yarn ``` -------------------------------- ### Music Library Sorting Examples (JavaScript) Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Demonstrates how to specify sorting criteria for music library items. This includes single keys, keys with direction, and complex arrays for multi-level sorting. These examples are crucial for implementing ordered lists of tracks, albums, or artists. ```javascript // Single sort key (descending by default) sortBy: 'artist' // Single sort key with direction sortBy: ['artist', true] // ascending sortBy: ['artist', false] // descending // Multiple sort criteria sortBy: [ ['artist', true], ['album', true], 'duration' ] ``` -------------------------------- ### Basic Usage of Music Library Functions Source: https://github.com/nodefinity/react-native-music-library/blob/main/README.md Demonstrates how to import and use core functions like getTracksAsync, getAlbumsAsync, and getArtistsAsync to retrieve music data. Shows an example of sorting albums by title. ```javascript import { getTracksAsync, getAlbumsAsync, getArtistsAsync } from '@nodefinity/react-native-music-library'; // Get tracks const tracks = await getTracksAsync(); // Get albums with sorting const albums = await getAlbumsAsync({ sortBy: ['title', true], // Sort by title ascending first: 50 }); // Get artists const artists = await getArtistsAsync(); ``` -------------------------------- ### Basic Usage of React Native Music Library APIs Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/intro.md Demonstrates how to import and use core functions like getTracksAsync, getAlbumsAsync, and getArtistsAsync from the library to retrieve music data. It includes examples of basic retrieval and retrieval with sorting options. ```javascript import { getTracksAsync, getAlbumsAsync, getArtistsAsync } from '@nodefinity/react-native-music-library'; // Get all tracks const tracks = await getTracksAsync(); // Get albums with sorting const albums = await getAlbumsAsync({ sortBy: ['title', true], // Sort by title ascending first: 50 }); // Get artists const artists = await getArtistsAsync(); ``` -------------------------------- ### GET /tracks Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves music tracks from the device with pagination, sorting, and filtering options. Returns a paginated result with cursor support for efficient loading of large collections. ```APIDOC ## GET /tracks ### Description Retrieves music tracks from the device with pagination, sorting, and filtering options. Returns a paginated result with cursor support for efficient loading of large collections. ### Method GET ### Endpoint /tracks ### Parameters #### Query Parameters - **first** (number) - Optional - The number of tracks to retrieve. Defaults to 20. - **sortBy** (array) - Optional - An array of sorting criteria. Each criterion can be a string (field name, defaults to descending) or an array `[fieldName, ascendingBoolean]`. Example: `[['artist', true], ['album', true], 'duration']` - **directory** (string) - Optional - Filters tracks by a specific directory. - **after** (string) - Optional - A cursor for pagination, used to fetch the next page of results. ### Request Example ```javascript // Basic usage const result = await getTracksAsync(); // Advanced usage const tracks = await getTracksAsync({ first: 50, sortBy: ['artist', true], directory: '/Music/Favorites', after: 'some-cursor-string' }); ``` ### Response #### Success Response (200) - **items** (array) - An array of Track objects. - **id** (string) - Unique identifier for the track. - **title** (string) - The title of the track. - **artist** (string) - The artist of the track. - **album** (string) - The album the track belongs to. - **artwork** (string) - File URI to the track's artwork. - **duration** (number) - Duration in seconds. - **url** (string) - File path of the track. - **createdAt** (number) - Unix timestamp when the track was added. - **modifiedAt** (number) - Unix timestamp when the track was last modified. - **fileSize** (number) - Size of the track file in bytes. - **hasNextPage** (boolean) - Indicates if there are more pages of results. - **endCursor** (string) - A cursor to retrieve the next page of results. #### Response Example ```json { "items": [ { "id": "track-id-123", "title": "Song Title", "artist": "Artist Name", "album": "Album Name", "artwork": "file:///path/to/artwork.jpg", "duration": 245, "url": "file:///path/to/song.mp3", "createdAt": 1678886400, "modifiedAt": 1678886400, "fileSize": 5242880 } ], "hasNextPage": true, "endCursor": "next-page-cursor" } ``` ``` -------------------------------- ### GET /tracks/:id/metadata Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves comprehensive metadata for a specific track including audio technical details, complete tag information, and lyrics. ```APIDOC ## GET /tracks/:id/metadata ### Description Retrieves comprehensive metadata for a specific track including audio technical details, complete tag information, and lyrics. ### Method GET ### Endpoint /tracks/:id/metadata ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the track. ### Request Example ```javascript const metadata = await getTrackMetadataAsync('track-id-123'); ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the track. - **duration** (number) - Duration in seconds. - **bitrate** (number) - Bitrate in kbps. - **sampleRate** (number) - Sample rate in Hz. - **channels** (number) - Number of audio channels. - **format** (string) - Audio format (e.g., 'mp3', 'flac'). - **title** (string) - The title of the track. - **artist** (string) - The artist of the track. - **album** (string) - The album the track belongs to. - **albumArtist** (string) - The album artist. - **composer** (string) - The composer of the track. - **lyricist** (string) - The lyricist of the track. - **year** (number) - The year the track was released. - **genre** (string) - The genre of the track. - **track** (number) - The track number within the album. - **disc** (number) - The disc number. - **comment** (string) - Any comments associated with the track. - **lyrics** (string) - The lyrics of the track, if available. #### Response Example ```json { "id": "track-id-123", "duration": 245, "bitrate": 320, "sampleRate": 44100, "channels": 2, "format": "mp3", "title": "Song Title", "artist": "Artist Name", "album": "Album Name", "albumArtist": "Album Artist Name", "composer": "Composer Name", "lyricist": "Lyricist Name", "year": 2020, "genre": "Pop", "track": 5, "disc": 1, "comment": "Example comment", "lyrics": "Verse 1... Chorus..." } ``` ``` -------------------------------- ### Get All Tracks Async Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves music tracks from the device with support for pagination, sorting, and directory filtering. It returns a paginated result, enabling efficient loading of large music collections. Dependencies include the '@nodefinity/react-native-music-library' package. ```javascript import { getTracksAsync } from '@nodefinity/react-native-music-library'; // Basic usage - get first 20 tracks (default) const result = await getTracksAsync(); console.log(result.items); // Array of Track objects console.log(result.hasNextPage); // true if more tracks available console.log(result.endCursor); // Cursor for next page // Advanced usage with all options const tracks = await getTracksAsync({ first: 50, // Get 50 tracks sortBy: ['artist', true], // Sort by artist ascending directory: '/Music/Favorites', // Filter by directory after: result.endCursor // Pagination cursor }); // Multiple sorting criteria const sortedTracks = await getTracksAsync({ first: 100, sortBy: [ ['artist', true], // First by artist ascending ['album', true], // Then by album ascending 'duration' // Then by duration descending (default) ] }); // Example track object structure const track = tracks.items[0]; console.log({ id: track.id, title: track.title, artist: track.artist, album: track.album, artwork: track.artwork, // File URI to artwork duration: track.duration, // Duration in seconds url: track.url, // File path createdAt: track.createdAt, // Unix timestamp modifiedAt: track.modifiedAt, fileSize: track.fileSize // Size in bytes }); ``` -------------------------------- ### Get Albums by Artist Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves all albums from a specific artist. Returns complete album list without pagination. ```APIDOC ## GET /albums ### Description Retrieves all albums associated with a specific artist ID. This endpoint returns the complete list of albums without any pagination. ### Method GET ### Endpoint `/albums` ### Parameters #### Query Parameters - **artistId** (string) - Required - The unique identifier of the artist whose albums are to be retrieved. ### Request Example ``` GET /albums?artistId=some-artist-id ``` ### Response #### Success Response (200) - **albums** (array) - An array of album objects. Each album object may contain properties like `id`, `title`, `year`, `trackCount`, etc. #### Response Example ```json { "albums": [ { "id": "album-1", "title": "Greatest Hits", "year": 2020, "trackCount": 15 }, { "id": "album-2", "title": "Live in Concert", "year": 2019, "trackCount": 12 } ] } ``` ``` -------------------------------- ### Get Albums by Artist (JavaScript) Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves all albums for a given artist from the music library. It first fetches an artist and their ID, then uses that ID to get all associated albums. The code also demonstrates sorting albums by year, calculating total tracks, and finding the largest album based on track count. Requires '@nodefinity/react-native-music-library'. ```javascript import { getAlbumsByArtistAsync, getArtistsAsync } from '@nodefinity/react-native-music-library'; // First get an artist const artists = await getArtistsAsync({ sortBy: ['albumCount', false], first: 1 }); const artistId = artists.items[0].id; // Get all albums by the artist const albums = await getAlbumsByArtistAsync(artistId); // Display artist's discography console.log(`Artist: ${artists.items[0].title}`); console.log(`Total albums: ${albums.length}\n`); // Sort albums by year const sortedAlbums = albums .filter(album => album.year) .sort((a, b) => a.year - b.year); sortedAlbums.forEach(album => { console.log(`${album.year} - ${album.title} (${album.trackCount} tracks)`); }); // Calculate total tracks across all albums const totalTracks = albums.reduce((sum, album) => sum + album.trackCount, 0); console.log(`\nTotal tracks: ${totalTracks}`); // Find most comprehensive album const largestAlbum = albums.reduce((max, album) => album.trackCount > max.trackCount ? album : max , albums[0]); console.log(`Largest album: ${largestAlbum.title} (${largestAlbum.trackCount} tracks)`); ``` -------------------------------- ### Get Albums By Artist Async - React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Retrieves all albums created by a specific artist, identified by their artist ID. Returns a promise that resolves to an array of Album objects. ```javascript import { getAlbumsByArtistAsync } from '@nodefinity/react-native-music-library'; const albums = await getAlbumsByArtistAsync('artist-id-123'); ``` -------------------------------- ### Get Music Artists Async - React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Retrieves artists from the device's music library. Supports pagination and sorting by criteria such as track count. Returns a promise that resolves to an ArtistResult object. ```javascript import { getArtistsAsync } from '@nodefinity/react-native-music-library'; // Get all artists const result = await getArtistsAsync(); // Get artists with sorting const artists = await getArtistsAsync({ first: 20, sortBy: ['trackCount', false] // Sort by track count descending }); ``` -------------------------------- ### Get Tracks by Artist with Sorting and Pagination (JavaScript) Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Fetches tracks associated with a specific artist, supporting pagination and sorting. This is ideal for artist detail pages. Sorting options include album and track title. Pagination is managed using cursors. ```javascript import { getTracksByArtistAsync, getArtistsAsync } from '@nodefinity/react-native-music-library'; // First get an artist const artists = await getArtistsAsync({ first: 1 }); const artistId = artists.items[0].id; // Get artist's tracks sorted by album const tracks = await getTracksByArtistAsync(artistId, { first: 100, sortBy: [ ['album', true], ['title', true] ] }); // Group tracks by album const tracksByAlbum = tracks.items.reduce((acc, track) => { if (!acc[track.album]) { acc[track.album] = []; } acc[track.album].push(track); return acc; }, {}); // Display artist discography console.log(`Artist: ${artists.items[0].title}`); Object.keys(tracksByAlbum).forEach(albumName => { console.log(` Album: ${albumName}`); tracksByAlbum[albumName].forEach(track => { console.log(` - ${track.title}`); }); }); // Pagination example for artists with many tracks let cursor = undefined; let allTracks = []; do { const result = await getTracksByArtistAsync(artistId, { first: 50, after: cursor, sortBy: ['createdAt', false] // Newest first }); allTracks = allTracks.concat(result.items); cursor = result.endCursor; } while (tracks.hasNextPage); ``` -------------------------------- ### Get Music Albums Async - React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Retrieves albums from the device's music library. Supports pagination and sorting by criteria such as track count. Returns a promise that resolves to an AlbumResult object. ```javascript import { getAlbumsAsync } from '@nodefinity/react-native-music-library'; // Get all albums const result = await getAlbumsAsync(); // Get albums with sorting const albums = await getAlbumsAsync({ first: 30, sortBy: ['trackCount', false] // Sort by track count descending }); ``` -------------------------------- ### Get Track Metadata Async Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves comprehensive metadata for a specific track, including audio technical details, complete tag information, and lyrics. Requires a track ID as input. Dependencies include the '@nodefinity/react-native-music-library' package. ```javascript import { getTrackMetadataAsync } from '@nodefinity/react-native-music-library'; // Get detailed metadata for a specific track const metadata = await getTrackMetadataAsync('track-id-123'); // Access audio header information console.log({ duration: metadata.duration, // Duration in seconds bitrate: metadata.bitrate, // Bitrate in kbps (e.g., 320) sampleRate: metadata.sampleRate, // Sample rate in Hz (e.g., 44100) channels: metadata.channels, // Number of channels (1=mono, 2=stereo) format: metadata.format // Audio format (e.g., 'mp3', 'flac') }); // Access tag information console.log({ title: metadata.title, artist: metadata.artist, album: metadata.album, albumArtist: metadata.albumArtist, composer: metadata.composer, lyricist: metadata.lyricist, year: metadata.year, genre: metadata.genre, track: metadata.track, // Track number in album disc: metadata.disc, // Disc number comment: metadata.comment }); // Display lyrics if available if (metadata.lyrics) { console.log('Lyrics:', metadata.lyrics); } ``` -------------------------------- ### Get All Artists with Sorting and Pagination (JavaScript) Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Fetches artist data from the music library, including album and track counts. Supports sorting by track count or album count, and allows for multiple sorting criteria. Pagination is handled via cursors. Artist objects contain ID, title, album count, and track count. ```javascript import { getArtistsAsync } from '@nodefinity/react-native-music-library'; // Basic usage const result = await getArtistsAsync(); // Sort by most popular artists (by track count) const popularArtists = await getArtistsAsync({ first: 50, sortBy: ['trackCount', false] // Artists with most tracks first }); // Sort by most prolific artists (by album count) const prolificArtists = await getArtistsAsync({ first: 50, sortBy: ['albumCount', false] }); // Multiple sorting: by album count, then track count const artists = await getArtistsAsync({ first: 100, sortBy: [ ['albumCount', false], ['trackCount', false] ] }); // Example artist object const artist = artists.items[0]; console.log({ id: artist.id, title: artist.title, // Artist name albumCount: artist.albumCount, // Number of albums trackCount: artist.trackCount // Total tracks across all albums }); // Build artist statistics artists.items.forEach(artist => { const avgTracksPerAlbum = artist.trackCount / artist.albumCount; console.log(`${artist.title}: ${artist.albumCount} albums, ${avgTracksPerAlbum.toFixed(1)} tracks/album`); }); ``` -------------------------------- ### Get Tracks By Artist Async - React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Retrieves all tracks associated with a specific artist, identified by their artist ID. Supports options for pagination and sorting. Returns a promise that resolves to a TrackResult object. ```javascript import { getTracksByArtistAsync } from '@nodefinity/react-native-music-library'; const tracks = await getTracksByArtistAsync('artist-id-123', { first: 100, sortBy: ['album', true] }); ``` -------------------------------- ### Get Tracks By Album Async - React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Retrieves all tracks belonging to a specific album, identified by its album ID. Returns a promise that resolves to an array of Track objects. ```javascript import { getTracksByAlbumAsync } from '@nodefinity/react-native-music-library'; const tracks = await getTracksByAlbumAsync('album-id-123'); ``` -------------------------------- ### Get All Albums with Sorting and Pagination (JavaScript) Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves album information from the device's music library. Supports custom sorting by release year or track count, and provides full pagination capabilities using cursors. Album objects include ID, title, artist, artwork, track count, and release year. ```javascript import { getAlbumsAsync } from '@nodefinity/react-native-music-library'; // Basic usage - get first 20 albums const result = await getAlbumsAsync(); // Get albums with custom sorting const albums = await getAlbumsAsync({ first: 50, sortBy: ['year', false] // Sort by release year descending }); // Sort by popularity (track count) const popularAlbums = await getAlbumsAsync({ first: 30, sortBy: ['trackCount', false] // Albums with most tracks first }); // Pagination example let allAlbums = []; let cursor = undefined; let hasMore = true; while (hasMore) { const page = await getAlbumsAsync({ first: 50, after: cursor, sortBy: ['title', true] }); allAlbums = allAlbums.concat(page.items); cursor = page.endCursor; hasMore = page.hasNextPage; } // Example album object const album = albums.items[0]; console.log({ id: album.id, title: album.title, artist: album.artist, artwork: album.artwork, // Base64 or URI (optional) trackCount: album.trackCount, year: album.year // Release year (optional) }); ``` -------------------------------- ### Get Music Tracks Async - React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Retrieves music tracks from the device's music library. Supports pagination, sorting by various criteria, and filtering by directory. Returns a promise that resolves to a TrackResult object. ```javascript import { getTracksAsync } from '@nodefinity/react-native-music-library'; // Get all tracks const result = await getTracksAsync(); // Get tracks with options const tracks = await getTracksAsync({ first: 50, sortBy: ['artist', true], directory: '/Music/Favorites' }); ``` -------------------------------- ### Get Track Metadata Async - React Native Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Retrieves detailed metadata for a specific track using its ID. Returns a promise that resolves to a TrackMetadata object containing audio and tag information, such as lyrics and bitrate. ```javascript import { getTrackMetadataAsync } from '@nodefinity/react-native-music-library'; const metadata = await getTrackMetadataAsync('track-id-123'); console.log('Lyrics:', metadata.lyrics); console.log('Bitrate:', metadata.bitrate); ``` -------------------------------- ### Get Tracks by Album (JavaScript) Source: https://context7.com/nodefinity/react-native-music-library/llms.txt Retrieves all tracks belonging to a specific album. This function does not use pagination and returns tracks in their original album order. It requires an album ID as input. Track objects include title, artist, and duration. ```javascript import { getTracksByAlbumAsync, getAlbumsAsync } from '@nodefinity/react-native-music-library'; // First get albums const albums = await getAlbumsAsync({ first: 10 }); const albumId = albums.items[0].id; // Get all tracks from the album const tracks = await getTracksByAlbumAsync(albumId); // Display album tracklist console.log(`Album: ${albums.items[0].title}`); console.log(`Total tracks: ${tracks.length}`); tracks.forEach((track, index) => { console.log(`${index + 1}. ${track.title} - ${track.artist} (${Math.floor(track.duration / 60)}:${String(Math.floor(track.duration % 60)).padStart(2, '0')})`); }); // Calculate total album duration const totalSeconds = tracks.reduce((sum, track) => sum + track.duration, 0); const totalMinutes = Math.floor(totalSeconds / 60); console.log(`Total duration: ${totalMinutes} minutes`); ``` -------------------------------- ### Publish New Version with Release-it Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Initiates the process of publishing a new version of the library to npm using release-it. This script handles version bumping, tagging, and release creation. ```sh yarn release ``` -------------------------------- ### Run Unit Tests with Jest Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Executes the unit tests defined for the project using the Jest testing framework. This verifies the correctness of individual code components. ```sh yarn test ``` -------------------------------- ### Fix Linting Errors with ESLint Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Runs ESLint with the --fix flag to automatically correct most formatting and style issues in the project's code. ```sh yarn lint --fix ``` -------------------------------- ### Lint Project with ESLint Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Applies ESLint to check for code style and potential errors according to the project's linting rules. This helps maintain code quality and consistency. ```sh yarn lint ``` -------------------------------- ### ArtistOptions Interface - TypeScript Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Defines the options available for querying music artists. Includes parameters for pagination (after, first) and sorting (sortBy). ```typescript interface ArtistOptions { after?: string; // Cursor for pagination first?: number; // Max items to return (default: 20) sortBy?: SortByValue | SortByValue[]; } ``` -------------------------------- ### AlbumOptions Interface - TypeScript Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Defines the options available for querying music albums. Includes parameters for pagination (after, first) and sorting (sortBy). ```typescript interface AlbumOptions { after?: string; // Cursor for pagination first?: number; // Max items to return (default: 20) sortBy?: SortByValue | SortByValue[]; } ``` -------------------------------- ### Complete Music Player Implementation in JavaScript Source: https://context7.com/nodefinity/react-native-music-library/llms.txt This JavaScript code implements a full-featured music player component for React Native. It handles fetching music library data (tracks, albums, artists), playing music, managing playback state, searching tracks, creating genre-based playlists, and infinite scrolling for loading more tracks. It relies on the '@nodefinity/react-native-music-library' package for music-related operations. ```javascript import { getTracksAsync, getAlbumsAsync, getArtistsAsync, getTracksByAlbumAsync, getTracksByArtistAsync, getTrackMetadataAsync } from '@nodefinity/react-native-music-library'; import { useState, useEffect } from 'react'; // Music player component with full functionality function MusicPlayer() { const [tracks, setTracks] = useState([]); const [albums, setAlbums] = useState([]); const [artists, setArtists] = useState([]); const [currentTrack, setCurrentTrack] = useState(null); const [loading, setLoading] = useState(true); const [searchQuery, setSearchQuery] = useState(''); // Load initial music library useEffect(() => { async function loadLibrary() { try { setLoading(true); // Load all data in parallel const [tracksResult, albumsResult, artistsResult] = await Promise.all([ getTracksAsync({ first: 100, sortBy: ['title', true] }), getAlbumsAsync({ first: 100, sortBy: ['title', true] }), getArtistsAsync({ first: 100, sortBy: ['title', true] }) ]); setTracks(tracksResult.items); setAlbums(albumsResult.items); setArtists(artistsResult.items); } catch (error) { console.error('Failed to load music library:', error); } finally { setLoading(false); } } loadLibrary(); }, []); // Play specific track and load its metadata async function playTrack(track) { try { setCurrentTrack(track); // Load detailed metadata for lyrics, etc. const metadata = await getTrackMetadataAsync(track.id); console.log('Now playing:', { title: metadata.title, artist: metadata.artist, bitrate: metadata.bitrate, format: metadata.format }); if (metadata.lyrics) { console.log('Lyrics available'); } } catch (error) { console.error('Failed to load track metadata:', error); } } // Play entire album async function playAlbum(album) { try { const albumTracks = await getTracksByAlbumAsync(album.id); if (albumTracks.length > 0) { await playTrack(albumTracks[0]); } } catch (error) { console.error('Failed to load album tracks:', error); } } // Play artist's top tracks async function playArtist(artist) { try { const artistTracks = await getTracksByArtistAsync(artist.id, { first: 20, sortBy: ['createdAt', false] }); if (artistTracks.items.length > 0) { await playTrack(artistTracks.items[0]); } } catch (error) { console.error('Failed to load artist tracks:', error); } } // Search functionality function searchTracks(query) { return tracks.filter(track => track.title.toLowerCase().includes(query.toLowerCase()) || track.artist.toLowerCase().includes(query.toLowerCase()) || track.album.toLowerCase().includes(query.toLowerCase()) ); } // Create playlist by genre (requires loading metadata) async function createGenrePlaylist(targetGenre) { const genreTracks = []; for (const track of tracks.slice(0, 50)) { // Limit for performance try { const metadata = await getTrackMetadataAsync(track.id); if (metadata.genre.toLowerCase() === targetGenre.toLowerCase()) { genreTracks.push(track); } } catch (error) { console.error(`Failed to load metadata for ${track.title}`); } } return genreTracks; } // Load more tracks (infinite scroll) async function loadMoreTracks(currentCursor) { try { const moreTracks = await getTracksAsync({ first: 50, after: currentCursor, sortBy: ['title', true] }); setTracks(prevTracks => [...prevTracks, ...moreTracks.items]); return { hasMore: moreTracks.hasNextPage, newCursor: moreTracks.endCursor }; } catch (error) { console.error('Failed to load more tracks:', error); return { hasMore: false, newCursor: null }; } } return { tracks, albums, artists, currentTrack, loading, playTrack, playAlbum, playArtist, searchTracks, createGenrePlaylist, loadMoreTracks }; } // Usage example const player = MusicPlayer(); ``` -------------------------------- ### TrackOptions Interface - TypeScript Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Defines the options available for querying music tracks. Includes parameters for pagination (after, first), sorting (sortBy), and directory filtering. ```typescript interface TrackOptions { after?: string; // Cursor for pagination first?: number; // Max items to return (default: 20) sortBy?: SortByValue | SortByValue[]; directory?: string; // Directory path to search } ``` -------------------------------- ### Type Check Project with TypeScript Source: https://github.com/nodefinity/react-native-music-library/blob/main/CONTRIBUTING.md Runs TypeScript to perform static type checking on the project's code. This helps catch type-related errors before runtime. ```sh yarn typecheck ``` -------------------------------- ### Android Permissions for Music Library Source: https://github.com/nodefinity/react-native-music-library/blob/main/README.md Specifies the necessary permissions to be added to the AndroidManifest.xml file to allow the library to read audio files from external storage. ```xml ``` -------------------------------- ### Album Interface Definition (TypeScript) Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Defines the structure for an album, including its ID, title, artist, artwork, and track count. Optional fields for release year are also included. This interface is used to group tracks by their album. ```typescript interface Album { id: string; title: string; // Album name artist: string; // Primary artist artwork?: string; // Album artwork URI trackCount: number; // Number of tracks year?: number; // Release year } ``` -------------------------------- ### Artist Interface Definition (TypeScript) Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Defines the structure for an artist, including their ID, name, and counts for albums and tracks. This interface provides a summary of an artist's presence in the music library. ```typescript interface Artist { id: string; title: string; // Artist name albumCount: number; // Number of albums trackCount: number; // Total number of tracks } ``` -------------------------------- ### Track Interface Definition (TypeScript) Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Defines the structure for a single music track, including its ID, title, artist, artwork, album, duration, file path, and timestamps. This interface is fundamental for managing individual song entries in the library. ```typescript interface Track { id: string; title: string; // Track title artist: string; // Artist name artwork: string; // Artwork file URI album: string; // Album name duration: number; // Duration in seconds url: string; // File URL or path createdAt: number; // Date added (Unix timestamp) modifiedAt: number; // Date modified (Unix timestamp) fileSize: number; // File size in bytes } ``` -------------------------------- ### TrackMetadata Interface Definition (TypeScript) Source: https://github.com/nodefinity/react-native-music-library/blob/main/docs/docs/api.md Defines the structure for detailed metadata of a music track, including audio header information (duration, bitrate, format) and tag information (title, artist, genre, lyrics). This provides comprehensive details about a track's technical and artistic attributes. ```typescript interface TrackMetadata { id: string; // Track ID // Audio header duration: number; // Duration in seconds bitrate: number; // Bitrate in kbps sampleRate: number; // Sample rate in Hz channels: number; // Number of channels format: string; // Audio format // Tag info title: string; // Track title artist: string; // Artist name album: string; // Album name year: number; // Release year genre: string; // Music genre track: number; // Track number disc: number; // Disc number composer: string; // Composer lyricist: string; // Lyricist lyrics: string; // Lyrics content albumArtist: string; // Album artist comment: string; // Comment } ``` -------------------------------- ### Request Android Music Library Permissions (JavaScript) Source: https://context7.com/nodefinity/react-native-music-library/llms.txt This function requests necessary permissions to access the music library on Android. It differentiates between Android 13+ (READ_MEDIA_AUDIO) and older versions (READ_EXTERNAL_STORAGE). It returns a boolean indicating if the permission was granted, handling platform checks and potential errors. ```javascript import { PermissionsAndroid, Platform } from 'react-native'; // Request music library permissions on Android async function requestMusicPermissions() { if (Platform.OS !== 'android') { return true; } try { // For Android 13 (API 33) and above if (Platform.Version >= 33) { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.READ_MEDIA_AUDIO, { title: 'Music Library Permission', message: 'This app needs access to your music library to play songs.', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', } ); return granted === PermissionsAndroid.RESULTS.GRANTED; } // For Android 12 and below const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, { title: 'Storage Permission', message: 'This app needs access to your storage to read music files.', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', } ); return granted === PermissionsAndroid.RESULTS.GRANTED; } catch (error) { console.error('Permission request failed:', error); return false; } } // Complete initialization flow async function initializeMusicLibrary() { const hasPermission = await requestMusicPermissions(); if (!hasPermission) { console.error('Music library permission denied'); return null; } try { // Load initial music data const tracks = await getTracksAsync({ first: 50 }); console.log(`Loaded ${tracks.items.length} tracks`); return tracks; } catch (error) { console.error('Failed to load music library:', error); return null; } } // Usage in React component import { useEffect, useState } from 'react'; import { getTracksAsync } from '@nodefinity/react-native-music-library'; function MusicApp() { const [tracks, setTracks] = useState([]); const [permissionGranted, setPermissionGranted] = useState(false); useEffect(() => { async function setup() { const hasPermission = await requestMusicPermissions(); setPermissionGranted(hasPermission); if (hasPermission) { const result = await getTracksAsync({ first: 100 }); setTracks(result.items); } } setup(); }, []); if (!permissionGranted) { return Please grant music library permissions; } return ( Tracks: {tracks.length} {/* Render track list */} ); } ```