【发布时间】:2021-03-31 13:31:37
【问题描述】:
播放音频时崩溃:
我正在创建一个包含多个不同屏幕的音频剪辑的应用程序。我们正在使用 Testflight 在 iPhone/iPad 上测试该应用程序,并且在播放音频剪辑时出现间歇性崩溃。音频剪辑本身似乎没有任何问题,因为它们大部分时间都在工作,而且问题并不总是同一个音频剪辑。
我猜这可能是与new Sound 相关的内存泄漏,但我不确定如何对此进行测试。我还认为我通过确保在声音组件播放后和屏幕卸载时released 来解决这个问题。
在确保正确清理 this.sound 组件时,我是否遗漏了什么?
我的代码:
import React, { Component } from 'react';
var Sound = require('react-native-sound');
Sound.setCategory("Playback"); //Needed for audio to play on IOS devices
import {
Image,
ImageBackground,
SafeAreaView,
ScrollView,
View,
Text,
TouchableOpacity
} from 'react-native';
export default class AudioList extends Component {
constructor(props) {
super(props)
}
playAudio = (file) => {
console.log(file)
if (this.sound) {
console.log("SOUND")
try {
this.sound.release()
} catch (error) {
console.log("A sound release error has occured 111")
} finally {
this.sound = null
}
}
this.sound = new Sound('audio/' + file, Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('error', error);
this.sound = null;
} else {
this.sound.play(() => {
try {
if (this.sound) {
this.sound.release()
}
} catch (error) {
console.log("A sound release error has occured 222")
} finally {
this.sound = null
}
})
}
})
this.willBlurSubscription = this.props.navigation.addListener(
'blur',
() => {
try {
if (this.sound) {
this.sound.release()
}
} catch (error) {
console.log("A sound release error has occured 333")
} finally {
this.sound = null
}
}
)
}
componentWillUnmount() {
try {
this.willBlurSubscription &&
this.willBlurSubscription.remove &&
this.willBlurSubscription.remove()
} catch (error) {} finally {
this.willBlurSubscription = null
}
}
render() {
/* list and new_list removed for brevity */
/* styles removed for brevity */
let audio_clips = new_list.map((item, index) => {
return <View key={index}>
{item.audio ?
<TouchableOpacity onPress={()=>this.playAudio(item.audio)}>
<Image source={require('../assets/images/audio-icon.png')} />
</TouchableOpacity>
:
<View></View>
}
<Text>{item.text}</Text>
</View>
})
return (
<SafeAreaView>
<Text>{list.category_name}</Text>
<ImageBackground source={require('../assets/images/background.jpg')}>
<ScrollView>
<View>
{audio_clips}
</View>
</ScrollView>
</ImageBackground>
</SafeAreaView>
)
}
}
【问题讨论】:
-
你应该在 yojur 项目中添加 Sentry,它会检测到崩溃并给你提示:docs.sentry.io/platforms/react-native
标签: javascript ios react-native audio crash