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

React Native 0.74.5使用react-native-sound报IsAndroid为null错误求助

解决React Native 0.74.5 + react-native-sound 0.11.2 报错 "TypeError: Cannot read property 'IsAndroid' of null"

问题原因

该错误是因为react-native-sound模块未完成原生端初始化就调用了Sound.setCategory方法,导致内部依赖的IsAndroid属性所在对象为null。另外,react-native-sound 0.11.2版本发布时间较早,与React Native 0.74.5存在兼容性差异,也可能触发该问题。

解决方案

1. 延迟初始化音频类别

将Sound.setCategory的调用放在组件挂载完成后执行,避免模块未初始化时调用:

import { StyleSheet, Text, TouchableOpacity, View, useEffect } from 'react-native'
import Sound from 'react-native-sound'

export default function App() {
  useEffect(() => {
    // 在组件挂载后初始化音频类别
    Sound.setCategory('Playback')
  }, [])

  const playSound = () => {
    // 加载并播放本地MP3文件(确保文件已放入正确路径)
    const audio = new Sound('your-audio-file.mp3', Sound.MAIN_BUNDLE, (error) => {
      if (error) {
        console.error('音频加载失败:', error)
        return
      }
      // 开始播放
      audio.play((success) => {
        if (!success) {
          console.error('音频播放失败')
        }
        // 播放完成后释放资源
        audio.release()
      })
    })
  }

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={{ backgroundColor: 'lightblue', padding: 10, borderRadius: 10 }}
        onPress={playSound}
      >
        <Text>Test 1 - Sonido</Text>
      </TouchableOpacity>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

2. 重新安装并确认模块链接

虽然React Native 0.60+支持自动链接,但偶尔会出现链接异常,执行以下步骤修复:

# 卸载现有库
npm uninstall react-native-sound

# 重新安装
npm install react-native-sound@0.11.2

# 针对iOS,重新安装Pod
cd ios && pod install && cd ..

3. 升级到兼容版本

如果上述方法无效,尝试使用react-native-sound的最新兼容版本(若有),或者考虑使用替代库如react-native-audio-player、expo-av(适用于Expo项目)。

内容的提问来源于stack exchange,提问作者OscarG.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:52:35