在自定义React Native / Expo音频播放器组件中启用清理?

时间:2018-02-14 04:02:37

标签: javascript reactjs react-native jsx expo

我在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>
        )
      }
    }

这看起来像这样: Audio Player

这样可以正常使用,但我希望点击圆圈可以移动它并选择音频的播放位置。

谢谢, 埃里克

1 个答案:

答案 0 :(得分:1)

您可以使用react-native附带的滑块组件,而不是您自己的实现。请参阅文档here。实施应该是直截了当的。