React Native 之组件react-native-sound的使用

本文介绍了如何在React Native项目中使用react-native-sound组件,包括安装步骤、注意事项,以及针对旧版本React Native的特殊配置。特别强调了Android平台下音频文件的命名规范和存放位置。示例代码展示了组件的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在项目根目录下执行安装包下载

npm install react-native-sound --save
2.然后自动使用链接:

react-native link react-native-sound
3.我自己是执行完以上两个步骤后查看了一下目录中相对的js配置文档,都是自动配置好的,但是以防意外,还是建议需要再核对一下

编辑android/settings.gradle以声明项目目录:

include ':react-native-sound'
project(':react-native-sound').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sound/android')

编辑android/app/build.gradle以声明项目依赖关系:

dependencies {
  ...
  compile project(':react-native-sound')
}

编辑android/app/src/main/java/.../MainApplication.java注册本机模块:

... 
import  com.zmxv.RNSound.RNSoundPackage ; // < -  New 
...

public  class  MainApplication  extends  Application  implements  ReactApplication {
   ... 
  @Override 
  protected  List < ReactPackage >  getPackages(){
     return  Arrays < ReactPackage > asList(
         new  MainReactPackage(),
         new  RNSoundPackage()// < -  New
    );
  }


注意:官方文档说明如果是旧版本的需要再更改一下

对于旧版本的React Native,您需要修改MainActivity.java

... 
import  com.zmxv.RNSound.RNSoundPackage ; // < -  New 
...

public  class  MainActivity  extends  Activity  implements  DefaultHardwareBackBtnHandler {
   ... 
    @Override 
  protected  void  onCreateBundle  savedInstanceState){
     ... 
    mReactInstanceManager =  ReactInstanceManager 生成器()
      .setApplication(getApplication())
      ... 
      .addPackage(new  MainReactPackage())
      .addPackage(new  RNSoundPackage())// < -  New 
      ... 
  }




另官方的文档还有一项说明:

  • Android: Save your sound clip files under the directory android/app/src/main/res/raw. Note that files in this directory must be lowercase and underscored (e.g. my_file_name.mp3) and that subdirectories are not supported by Android.
但实际并不影响,自己新建的raw文件夹放进去的MP3.


执行效果如图:


index.android.js的文件原码

import React, {Component} from 'react';

import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Platform,
  AppRegistry
from 'react-native';
const Sound = require('react-native-sound');

const Button = ({title, onPress}) => (
  <TouchableOpacity onPress={onPress}>
    <Text style={styles.button}>{title}</Text>
  </TouchableOpacity>
);

const Header = ({children}) => (<Text style={styles.header}>{children}</Text>);

const Feature = ({title, onPress, description, buttonLabel = "PLAY"}) => (
  <View style={styles.feature}>
    <Header>{title}123</Header>
    <Button title={buttonLabel} onPress={onPress}/>
  </View>);

const requireAudio = require('./advertising.mp3');

export default class App extends Component {

  constructor(props) {
    super(props);

    Sound.setCategory('Ambient'true); // true = mixWithOthers

    this.playSoundBundle = () => {
      const s = new Sound('advertising.mp3', Sound.MAIN_BUNDLE, (e=> {
        if (e) {
          console.log('error', e);
        } else {
          s.setSpeed(1);
          console.log('duration', s.getDuration());
          s.play(() => s.release()); // Release when it's done so we're not using up resources
        }
      });
    };

    this.playSoundLooped = () => {
      if (this.state.loopingSound) {
        return;
      }
      const s = new Sound('advertising.mp3', Sound.MAIN_BUNDLE, (e=> {
        if (e) {
          console.log('error', e);
        }
        s.setNumberOfLoops(-1);
        s.play();
      });
      this.setState({loopingSound: s});
    };

    this.stopSoundLooped = () => {
      if (!this.state.loopingSound) {
        return;
      }

      this.state.loopingSound
        .stop()
        .release();
      this.setState({loopingSound: null});
    };

    this.playSoundFromRequire = () => {
      const s = new Sound(requireAudio, (e=> {
        if (e) {
          console.log('error', e);
          return;
        }

        s.play(() => s.release());
      });
    };

    this.state = {
      loopingSound: undefined,
    };
  }

  renderiOSOnlyFeatures() {
    return [
      <Feature key="require" title="Audio via 'require' statement" onPress={this.playSoundFromRequire}/>,
    ]
  }

  render() {
    return <View style={styles.container}>
      <Feature title="Main bundle audio" onPress={this.playSoundBundle} buttonLabel={'重置'}/>
      {this.state.loopingSound
        ? <Feature title="Main bundle audio (looped)" buttonLabel={'暂停'} onPress={this.stopSoundLooped}/>
        : <Feature title="Main bundle audio (looped)" buttonLabel={'播放'} onPress={this.playSoundLooped}/>
      }
      { Platform.OS === 'ios' ? this.renderiOSOnlyFeatures() : null }
    </View>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    fontSize: 20,
    backgroundColor: 'silver',
    padding: 5,
  },
  header: {
    borderBottomWidth: 1,
    borderBottomColor: 'black',
  },
  feature: {
    padding: 20,
    alignSelf: 'stretch',
  }
});


AppRegistry.registerComponent('App', () => App);


原项目git仓库地址:https://github.com/zmxv/react-native-sound

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值