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

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

你可能感兴趣的:(React-Native)