【问题标题】:React Native how to play a sound after an "onPress"?React Native 如何在“onPress”之后播放声音?
【发布时间】:2019-04-07 07:37:19
【问题描述】:

这是我的一些代码:

<TouchableOpacity
       style={styles.button}
       onPress={this.onPress}
       >
       <Text> Play Sound </Text>
</TouchableOpacity>

我想编写一个函数“onPress”来播放.mp3 声音。 我已经导入了 react-native-sound 并准备好了我的 .mp3 文件,只是不知道调用 onPress 函数后如何播放声音。

【问题讨论】:

标签: react-native onpress react-native-sound


【解决方案1】:

在我看来,如果你想听声音,你可以试试这个。 语法 = 反应。

Import Sound from "react-native-sound";

Sound.setCategory('Playback');
const whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {

if (error) {
 console.log('failed to load the sound', error);
 return;
 };
whoosh.play((success) => {
  if (success) {
  console.log('successfully finished playing');
  } else {
   console.log('playback failed due to audio decoding errors');
   reset the player to its uninitialized state (android only)
   whoosh.reset();
}

【讨论】:

    【解决方案2】:

    最简单的方法是首先创建一个新实例,例如 Following。 在构造函数中创建 this 以在组件挂载时加载它 注意:请将您的 mp3 或 wav 文件放在 android/app/src/main/res/raw 中

    const whoosh  = new Sound('swoosh.mp3', Sound.MAIN_BUNDLE);
    

    只需在你的函数中调用它

    whoosh.play()
    

    【讨论】:

    • 这与已有的答案有何不同?
    • 这只是一个两行代码兄弟,很容易理解
    • 在我的实验中,声音文件必须引用为./swoosh.mp3,而不是swoosh.mp3(注意前面的点和斜线),否则捆绑时会抛出错误(TypeError:无法读取属性DeltaPacher.js:77 中未定义的“concat”)
    【解决方案3】:
    1. Npm install 'react-native-sound' 并链接到您的项目。
    2. 从 react-native-sound 导入声音

      从“react-native-sound”导入声音;

    3. 将您的 mp3 文件放入文件夹并注明路径:

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

    4. 将此代码放在“onPress”函数中。

      const s = new Sound(requireAudio, (e) => { 如果(e){ console.log('声音错误', e); 返回; } s.play(() => s.release()); });

    【讨论】:

      猜你喜欢
      • 2019-05-13
      • 2021-07-16
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多