我想在React Native中播放声音。
我已经尝试在zmxv/react-native-sound中进行阅读,但是作为像我这样的初学者,这些文档让我很困惑如何在React Native代码中应用它。
在我尝试this one以便对事件做出本地播放声音并编写如下代码之前,
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>
)
}
}
这是我放置音频的地方:
MyProject / android / app / src / main / res / raw / motorcycle.mp3
项目结构
那么,我的代码有什么问题?
答案 0 :(得分:2)
这将预加载声音,当您按播放时,它将播放声音。
AttributeError Traceback (most recent call last)
<ipython-input-3-c49da396977d> in <module>
40 p6.start()
41
---> 42 p7 = Process(target = automl_automl_accuracy(forex_list_accuracy_7, y))
43 print('automl_automl_accuracy:', automl_automl_accuracy.accuracy)
44 p7.start()
<string> in automl_automl_accuracy(DF_list, x)
AttributeError: 'NoneType' object has no attribute 'as_data_frame'
答案 1 :(得分:2)
非常感谢谁回答了这个问题,但是我已经用一个简单的方法解决了这个问题:
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>
)
}
}
答案 2 :(得分:1)
尝试使用以下代码播放声音:
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
解决了答案 3 :(得分:0)
对于iOS,对我有用的是:
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();