我正在尝试使用 expo/av 在 React - Native 中创建音乐播放器。但我正面临错误
error while playing the audio TypeError: sound.current.playAsync is not a function
下面是我的代码:
import React, { useState, useEffect } from "react";
import { View, StyleSheet, TouchableOpacity, Text } from "react-native";
import { Audio } from "expo-av";
import Icon from "../icon/icon";
import { Slider } from "react-native-range-slider-expo";
import { AntDesign } from '@expo/vector-icons';
const SampleTrack = require("../../assets/audioFile/Hello.mp3")
const AudioPlayer = () => {
const [Loaded,SetLoaded] = useState(false);
const [Loading,SetLoading] = useState(false);
const [Playing,SetPlaying] = useState(false);
const sound = React.useRef(new Audio.Sound());
useEffect(()=>{
LoadAudio();
},[]);
const PlayAudio = async ()=>{
try{
const result = await sound.current.getStatusAsync();
if(result.isLoaded){
if(result.isPlaying === false){
sound.current.playAsync();
SetPlaying(true)
}
}
}catch(e){
console.log('error while playing the audio',e)
}
};
const PauseAudio = async() =>{
try{
const result = await sound.current.getStatusAsync();
if(result.isLoaded){
if(result.isPlaying === true){
sound.current.pauseAsync();
}
}
}catch(e){
console.log("error while pausing the audio",e)
}
}
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('Unknown error while loading audio')
}else{
SetLoading(false);
SetLoaded(true)
}
}catch(e){
console.log('error while loading the audio',e)
SetLoading(false)
}
}else{
console.log(checkLoading)
SetLoading(false)
}
}
return (
<View style={styles.container}>
{Playing ? <View style={styles.button}>
<TouchableOpacity onPress={() => PauseAudio()}>
<AntDesign name="pause" size={24} color="black" />
</TouchableOpacity>
</View> : <View style={styles.button}>
<TouchableOpacity onPress={() => PlayAudio()}>
<Icon name="playButton" fill={"#858787"} height={20} />
</TouchableOpacity>
</View>}
<View style={styles.lineContainer}>
{/* <View style={styles.line}>
<View style={styles.progressbar}></View>
<View style={styles.bulb}></View>
</View> */}
<Seekbar></Seekbar>
</View>
</View>
);
};
我正在尝试按照文档使用异步函数(使用 ref 来初始化音频类并使用 require 来获取本地存储的音频,它似乎不起作用)但其中任何一个都无法正常工作,我是认真的卡住 。任何形式的帮助表示赞赏。