暂停反应原生博览会音频?
Posted
技术标签:
【中文标题】暂停反应原生博览会音频?【英文标题】:Pausing react native expo Audio? 【发布时间】:2021-06-18 23:13:43 【问题描述】:我在运行音频时没有问题,但在暂停它时遇到了问题。如果有人可以提供帮助,那就太好了。
async function playMusic()
const soundObject = new Audio.Sound();
console.log("Being hit")
try
await soundObject.loadAsync(uri:'https://firebasestorage.googleapis.com/v0/b/o/myFolder%2FMello%20C%20-%20Easy.mp3?c4e-4bf8-b8ea-dcc201efff44');
await soundObject.playAsync();
catch (error)
alert("Error" + error.message)
async function stopMusic()
console.log("Not Being hit")
const soundObject = new Audio.Sound();
try
await soundObject.loadAsync(uri:'https://firebasestorage.googleapis.com/v03?alt=media&token=e44f7b2f-8c4e-4bf8-b8ea-dcc201efff44');
await soundObject.stopAsync();
catch (error)
alert("Error" + error.message)
【问题讨论】:
【参考方案1】:请注意,我们永远不应该将 Sound 实例创建为状态变量。因为只要有重新渲染,它就会重新初始化声音实例。
您应该创建一个ref
变量并使用它,
const sound = React.useRef(new Audio.Sound());
Working Example
暂停/播放音乐的实现
import * as React from 'react';
import
Text,
View,
StyleSheet,
ActivityIndicator,
Button,
from 'react-native';
import Constants from 'expo-constants';
import Audio from 'expo-av';
const SampleTrack = require('./Roses.m4a');
export default function App()
const [Loaded, SetLoaded] = React.useState(false);
const [Loading, SetLoading] = React.useState(false);
const sound = React.useRef(new Audio.Sound());
React.useEffect(() =>
LoadAudio();
, []);
const PlayAudio = async () =>
try
const result = await sound.current.getStatusAsync();
if (result.isLoaded)
if (result.isPlaying === false)
sound.current.playAsync();
catch (error)
;
const PauseAudio = async () =>
try
const result = await sound.current.getStatusAsync();
if (result.isLoaded)
if (result.isPlaying === true)
sound.current.pauseAsync();
catch (error)
;
const LoadAudio = async () =>
SetLoading(true);
const checkLoading = await sound.current.getStatusAsync();
if (checkLoading.isLoaded === false)
try
const result = await sound.current.loadAsync(SampleTrack, , true);
if (result.isLoaded === false)
SetLoading(false);
console.log('Error in Loading Audio');
else
SetLoading(false);
SetLoaded(true);
catch (error)
console.log(error);
SetLoading(false);
else
SetLoading(false);
;
return (
<View style=styles.container>
<View style=styles.AudioPLayer>
Loading ? (
<ActivityIndicator size='small' color='red' />
) : (
<>
Loaded === false ? (
<>
<ActivityIndicator />
<Text>Loading Song</Text>' '
</>
) : (
<>
<Button title="Play Song" onPress=PlayAudio />
<Button title="Pause Song" onPress=PauseAudio />
</>
)
</>
)
</View>
</View>
);
const styles = StyleSheet.create(
container:
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
,
AudioPLayer:
width: '100%',
height: 50,
alignItems: 'center',
,
);
【讨论】:
谢谢 Kartikey,你太棒了。 欢迎您!如果您的问题得到解决,请将此答案标记为已接受。 抱歉,我还是 Stack Overflow 的新手以上是关于暂停反应原生博览会音频?的主要内容,如果未能解决你的问题,请参考以下文章