如何在React Native中播放声音?

编程入门 行业动态 更新时间:2024-10-18 22:31:57
本文介绍了如何在React Native中播放声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在React Native中播放声音.

我已经尝试在

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

解决方案

这将预加载声音,当您按播放时将播放声音.

导出默认类MovieList扩展Component {componentDidMount(){this.hello = new Sound('whoosh.mp3',Sound.MAIN_BUNDLE,(error)=> {如果(错误){console.log('无法加载声音',错误);返回;}});}handlePress(){this.hello.play((success)=> {如果(!成功){console.log('声音没有播放')}})}使成为() {const {movie} = this.props返回 (< TouchableOpacity onPress = {this.handlePress.bind(this)}><查看><文本>开始</文本></View></TouchableOpacity>)}}

如果您要从声音列表中播放音轨,请检查有关详细信息的gitHub链接代码

I want to play a sound in 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.

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

Project structure

So, what's wrong in my code?

解决方案

This will preload the sound and When you press the play 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 Track from a List of sounds please check this gitHub gist link for detailed code

更多推荐

如何在React Native中播放声音?

本文发布于:2023-11-14 15:16:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587766.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:声音   如何在   React   Native

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!