在事件中反应本机播放声音

gam*_*mer 21 react-native

我有一个组件,如:

import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'


class MovieList extends Component {


    handlePress() {
        // Play some sound here
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View style={styles.movie}>
                    <Text style={styles.name}>{movie.name}</Text>
                    <View style={styles.start}>
                        <Text style={styles.text}>Start</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里当我触摸时view我想播放一些声音.我搜索了它,但没有找到任何适当的答案

无论如何,当我按下某些东西时我能发出声音吗?我怎样才能做到这一点 ?

Tom*_*ers 15

查看React Native Sound - 一个用于访问设备音频控件的跨平台组件.

您可以像这样使用它:

const Sound = require('react-native-sound')

let hello = new Sound('hello.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log(error)
  }
})

hello.play((success) => {
  if (!success) {
    console.log('Sound did not play')
  }
})
Run Code Online (Sandbox Code Playgroud)

  • 您可能也想要声音,否则可能会出错.https://github.com/zmxv/react-native-sound/issues/120 (2认同)

Nia*_*ais 7

您可以尝试来自expo-sdk的音频组件。

在此处查看示例。

它适用于SDK 18。