简体   繁体   English

如何在 React Native 中播放声音?

[英]How to play sound in React Native?

I want to play a sound in React Native.我想在 React Native 中播放声音。

I have try to read here in zmxv/react-native-sound , but as a beginner like me, that's documentation make me confused how to apply that in React Native code.我已经尝试在zmxv/react-native-sound中阅读这里,但作为像我这样的初学者,这些文档让我困惑如何在 React Native 代码中应用它。

Before I have try this one to make react native play sound on event and make a code like this:在我尝试这个使事件响应本机播放声音并制作如下代码之前:

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>
        )
    }
}

And this is where I put my audio:这是我放置音频的地方:

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

Project structure项目结构

项目结构

So, what's wrong in my code?那么,我的代码有什么问题?

This will preload the sound and when you press the play button it will play it.这将预加载声音,当您按下播放按钮时,它将播放。

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>
        )
    }
}

If you are looking to play sound tracks from a list of sounds please check this gist for detailed code.如果您希望从声音列表中播放音轨,请查看此要点以获取详细代码。

Thanks very much who has answer to this question, but i have resolve this with this simple one:非常感谢谁回答了这个问题,但我已经用这个简单的问题解决了这个问题:

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>
        )
    }
}

Try this code for play sound:尝试使用此代码播放声音:

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

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

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

For iOS what worked for me is the following:对于 iOS,对我有用的是:

  1. Checked that my resource file was being played in xCode检查我的资源文件是否正在 xCode 中播放
    • Open xCode打开 xCode
    • Select the file选择文件
    • Click play in the xCode player在 xCode 播放器中单击播放
  2. Once it was playing sound (had issues with some files, possibly encoding),一旦播放声音(某些文件有问题,可能是编码问题),
    • Add the file as resource (Make sure is in Build Phases)将文件添加为资源(确保在构建阶段)
  3. Compile the project in xCode and run it from there在 xCode 中编译项目并从那里运行它
    • Note: Every time you change the resources or expect new resources you need to compile your Native application either by doing it from xCode or npm run ios注意:每次更改资源或期望新资源时,您都需要通过 xCode 或npm run ios来编译本机应用程序

This is my code:这是我的代码:

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();

if you are using Audio from Expo then this may help如果您使用的是来自 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")
        );
        // ...
    }
}

You only need one line of code to play the sound effect.只需要一行代码就可以播放音效。 On the top of the onPlayPress event handler, add the following:在 onPlayPress 事件处理程序的顶部,添加以下内容:

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

Notice how I used replayAsync instead of playAsync – it's because we may use this sound effect more than one time, and if you use playAsync and run it multiple times, it will only play the sound for the first time.请注意我是如何使用 replayAsync 而不是 playAsync 的——这是因为我们可能会多次使用这个音效,如果你使用 playAsync 并多次运行它,它只会在第一次播放声音。 It will come in handy later, and it's also useful for continuing with the Game screen.它稍后会派上用场,而且对于继续游戏屏幕也很有用。 See more full example 查看更多完整示例

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

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