You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Android端加载TensorFlow Lite模型文件失败求助

解决Android原生加载React Native Example中TFLite模型的问题

核心问题原因

React Native Example项目中的静态资源(比如你的./models/deepSpeech.tflite)不会自动打包到Android原生的assets目录,而AssetManager仅能访问Android项目src/main/assets下的文件,所以直接传入相对路径会触发文件找不到的错误。

解决方案步骤

1. 配置Example Android项目的资源目录

在./example/android/app/src/main下创建assets/models目录,将deepSpeech.tflite复制到该目录中。

2. 调整原生加载代码

修改Android原生方法,确保正确通过AssetManager读取文件,同时优化资源流的关闭逻辑:

@ReactMethod
public void loadTflite(String path, Promise promise) {
    try {
        AssetFileDescriptor fileDescriptor = context.getAssets().openFd(path);
        FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
        FileChannel fileChannel = inputStream.getChannel();
        long startOffset = fileDescriptor.getStartOffset();
        long declaredLength = fileDescriptor.getDeclaredLength();
        
        // 此处可初始化TFLite模型实例
        // Interpreter tflite = new Interpreter(fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength));
        
        promise.resolve(0);
        // 关闭资源流
        fileChannel.close();
        inputStream.close();
        fileDescriptor.close();
    } catch(Exception ex) {
        ex.printStackTrace();
        Log.e("Tflite loading Error", ex.getMessage());
        promise.reject("Tflite loading Error", ex.toString());
    }
}

3. 修改Example中的调用路径

在./example/src/App.tsx中,将传入的路径改为相对于assets目录的路径:

React.useEffect(() => {
    loadTflite('models/deepSpeech.tflite').then((rs) => {
      setResult("success")
    }).catch((e) => {
      console.error(`Failed to load the tflite. The error is ${e}`)
      setResult('Failed')
    })
}, []);

4. 可选:自动同步模型到Android assets

避免手动复制文件,可在Example的package.json中添加同步脚本:

"scripts": {
  "sync-models": "cp ./models/deepSpeech.tflite ./android/app/src/main/assets/models/"
}

执行npm run sync-models即可自动同步模型文件。

额外注意事项

  • 确保metro.config.js中已将tflite加入assetExts,避免RN打包时忽略该文件:
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

const config = {};

module.exports = mergeConfig(getDefaultConfig(__dirname), {
  resolver: {
    assetExts: [...getDefaultConfig(__dirname).resolver.assetExts, 'tflite'],
  },
});
  • 若希望模块本身内置模型(不依赖Example),可将模型放到模块的android/src/main/assets目录下,这样模块被引用时,模型会自动打包到宿主项目中。

内容的提问来源于stack exchange,提问作者Ma Zheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:05:28