我正在尝试使用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>
);
};
我正试图根据文档使用Async函数(使用ref初始化音频类,并使用require获取本地存储的音频,但它似乎不起作用(,但其中任何一个都不起作用,我被严重卡住了。任何形式的帮助都将不胜感激。
我遇到了同样的问题,还没有弄清楚如何让playAsync()
工作,但我找到了一个解决办法,那就是使用setStatusAsync()
,而不是任何方便的方法。
所以你可以尝试替换:
sound.current.playAsync()
带有:
sound.current.setStatusAsync({ shouldPlay: true })