繁体   English   中英

如何在 React Native 中播放声音?

[英]How to play sound in React Native?

我想在 React Native 中播放声音。

我已经尝试在zmxv/react-native-sound中阅读这里,但作为像我这样的初学者,这些文档让我困惑如何在 React Native 代码中应用它。

在我尝试这个使事件响应本机播放声音并制作如下代码之前:

import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
const Sound = require('react-native-sound')


export default class MovieList extends Component {

    handlePress() {
        // Play some sound here
        let hello = new Sound('motorcycle.mp3', Sound.MAIN_BUNDLE, (error) => {
            if (error) {
              console.log(error)
            }
          })

          hello.play((success) => {
            if (!success) {
              console.log('Sound did not play')
            }
          })
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View>
                      <Text>Start</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

这是我放置音频的地方:

我的项目/android/app/src/main/res/raw/motorcycle.mp3

项目结构

项目结构

那么,我的代码有什么问题?

这将预加载声音,当您按下播放按钮时,它将播放。

export default class MovieList extends Component {
    componentDidMount(){
      this.hello = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
        if (error) {
          console.log('failed to load the sound', error);
          return;
        }
      });
    }
    
    
    handlePress() {
      this.hello.play((success) => {
        if (!success) {
          console.log('Sound did not play')
        }
      })
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View>
                      <Text>Start</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

如果您希望从声音列表中播放音轨,请查看此要点以获取详细代码。

非常感谢谁回答了这个问题,但我已经用这个简单的问题解决了这个问题:

import React, { Component } from 'react'
import { Text, View, TouchableOpacity } from 'react-native'
import Sound from 'react-native-sound';

export default class MovieList extends Component {

    sound = new Sound('motorcycle.mp3');

    playSound = () => {
        this.sound.play()
    }

    render() {
        return (
            <View>
                <TouchableOpacity onPress={this.playSound}>
                    <View>
                        <Text>Start</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
}

尝试使用此代码播放声音:

setTimeout(() => {
     var sound = new Sound("motorcycle.mp3",Sound.MAIN_BUNDLE, (error) => {
                     /* ... */
     });

     setTimeout(() => {
         sound.play((success) => {
                  /* ... */
         });
    }, 100);
}, 100);

这是 hacky 并通过https://github.com/zmxv/react-native-sound/issues/89#issuecomment-276678935解决

对于 iOS,对我有用的是:

  1. 检查我的资源文件是否正在 xCode 中播放
    • 打开 xCode
    • 选择文件
    • 在 xCode 播放器中单击播放
  2. 一旦播放声音(某些文件有问题,可能是编码问题),
    • 将文件添加为资源(确保在构建阶段)
  3. 在 xCode 中编译项目并从那里运行它
    • 注意:每次更改资源或期望新资源时,您都需要通过 xCode 或npm run ios来编译本机应用程序

这是我的代码:

const sound = new Sound(
    "myFile.mp3",
    Sound.MAIN_BUNDLE,
    error => {
      if (error) {
        console.log("failed to load the sound", error);
        return;
      }
      sound.play(() => sound.release());
    }
  );
// The play dispatcher
sound.play();

如果您使用的是来自 Expo 的音频,那么这可能会有所帮助

async componentWillMount() {
    this.backgroundMusic = new Audio.Sound();
    this.buttonFX = new Audio.Sound();
    try {
        await this.backgroundMusic.loadAsync(
            require("../../assets/music/Komiku_Mushrooms.mp3")
        );
        await this.buttonFX.loadAsync(
            require("../../assets/sfx/button.wav")
        );
        // ...
    }
}

只需要一行代码就可以播放音效。 在 onPlayPress 事件处理程序的顶部,添加以下内容:

onPlayPress = () => {
    this.buttonFX.replayAsync();
    // ...
}

请注意我是如何使用 replayAsync 而不是 playAsync 的——这是因为我们可能会多次使用这个音效,如果你使用 playAsync 并多次运行它,它只会在第一次播放声音。 它稍后会派上用场,而且对于继续游戏屏幕也很有用。 查看更多完整示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM