我在React Native中有一个音频播放器(使用Expo的音频API),工作正常。这是我的AudioPlayer
课程:
class AudioPlayer extends React.Component {
constructor(props) {
super(props);
this.state = {
isPlaying: false,
position: 0,
timeLeft: ""
};
this.loadAudio = this.loadAudio.bind(this);
this.toggleAudioPlayback = this.toggleAudioPlayback.bind(this);
this.getStatus = this.getStatus.bind(this);
}
componentDidMount() {
this.loadAudio();
this.interval = setInterval(() => this.getStatus(), 800);
}
componentWillUnmount() {
clearInterval(this.interval);
this.soundObject.stopAsync();
}
async loadAudio() {
this.soundObject = new Audio.Sound();
try {
await this.soundObject.loadAsync(this.props.source);
} catch (e) {
console.log('ERROR Loading Audio', e);
}
this.getStatus();
}
toggleAudioPlayback() {
this.setState({
isPlaying: !this.state.isPlaying,
}, () => (this.state.isPlaying
? this.soundObject.playAsync()
: this.soundObject.pauseAsync()));
}
getStatus = async () => {
var status = await this.soundObject.getStatusAsync();
var percentage = (status["positionMillis"] / status["durationMillis"] * 100);
var remainingTime = msToTime(status["durationMillis"] - status["positionMillis"]);
this.setState({position: percentage, timeLeft: remainingTime});
}
render() {
return (
<View style={{flex: 1, flexDirection: 'row', alignItems: 'center', backgroundColor: 'rgba(0, 0, 0, 0.7)', borderRadius: 5, padding: 5, paddingRight: 12}}>
<Entypo name={this.state.isPlaying ? "controller-paus" : "controller-play"} color='#dedede' size={25} onPress={this.toggleAudioPlayback} />
<View style={{flex: 1, height: 4, backgroundColor: '#d6d6d6', alignItems: 'center', flexDirection: 'row'}}>
<View style={{position: 'absolute', width: `${this.state.position}%`, left: 0, height: 4, backgroundColor: orangeColor}} />
<View style={{position: 'absolute', left: `${this.state.position}%`, borderRadius: 100/2, width: 10, height: 10, backgroundColor: orangeColor}} />
</View>
<View style={{width: 5}} />
<Text style={{color: 'white', width: 83, textAlign: 'right'}}>-{this.state.timeLeft}</Text>
</View>
)
}
}
这样可以正常使用,但我希望点击圆圈可以移动它并选择音频的播放位置。
谢谢, 埃里克