Skip to content

[Fix] Supports loading local audio directly via resource ID (compatible with RN 0.81.4) #882

Description

@cnlile

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch react-native-sound@0.11.2 for the project I'm working on.

I encountered an issue when loading local audio using react-native-sound in React Native 0.81.4:

  • The local audio obtained via require('../assets/audio/test.mp3') is a "resource ID (number)," and directly passing it to new Sound() will result in an error stating "file not found.";
  • The original library requires manual resolution of IDs to URIs using RN's built-in resolveAssetSource, which is cumbersome and error-prone;
  • My modification involves automatically handling resource ID resolution within the library, ensuring compatibility with the local resource loading logic of higher RN versions (≥0.80.x).

Here is the diff that solved my problem (modified node_modules/react-native-sound/sound.js):

--- a/node_modules/react-native-sound/sound.js
+++ b/node_modules/react-native-sound/sound.js

@@ -1,7 +1,10 @@
 var React = require('react-native');
 var NativeModules = React.NativeModules;
 var RNSound = NativeModules.RNSound;
-//var resolveAssetSource = require("react-native/Libraries/Image/resolveAssetSource"); // Annotate this line, it is old code
+var { Image } = require('react-native');

+// Custom resolveAssetSource to support RN 0.81+ resource ID (number)

function resolveAssetSource(asset) {
  // Scenario 1: The asset is a digital ID (RN 0.81+ format), resolved using Image.resolveAssetSource
  if (typeof asset === 'number') {
    try {
      const resolvedAsset = Image.resolveAssetSource(asset);
      return resolvedAsset;
    } catch (e) {
      console.warn('Failed to parse resource ID:', e);
      return null;
    }
  }

  // Scenario 2: The asset is an object (compatible with older versions of React Native)
  if (typeof asset === 'object' && asset !== null && asset.uri) {
    console.log('Object format resource parsing:', asset.uri);
    return asset;
  }

  // Scenario 3: The asset is a string path (returned directly)
  if (typeof asset === 'string') {
    return { uri: asset };
  }

  // Return null in other situations
  console.error('Resource parsing failed');
  return null;
}

This issue body was partially generated by patch-package.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions