我在运行音频时没有问题,但在暂停时遇到了问题。如果有人可以提供帮助,那就太好了。
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)
}
}
答案 0 :(得分:0)
看到我们永远不应该将 Sound 实例创建为状态变量。因为每当有重新渲染时,它都会重新初始化声音实例。
您应该创建一个 ref
变量并使用它,
const sound = React.useRef(new Audio.Sound());
暂停/播放音乐的实现
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',
},
});