Как я могу сделать индикатор выполнения песни для моего аудиоплеера? - PullRequest
2 голосов
/ 04 февраля 2020

Я сделал простой аудиоплеер, но теперь я хочу добавить индикатор выполнения песни, который заполняет временную шкалу во время воспроизведения песни, это мой html:

 <div id="ap-timeline" onClick={this.mouseMove} ref={(timeline) => { this.timeline = timeline }}>
   <div id="ap-handle" onMouseDown={this.mouseDown} ref={(handle) => { this.handle = handle }} />
   <div id="ap-handle-circle" onMouseDown={this.mouseDown} ref={(handleCircle) => { this.handleCircle = handleCircle }} />
 </div>

И это это мой CSS:

#ap-timeline{
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 550px;
  height: 4px;
  border-radius: 15px;
  background: $audio-slider-gray;   
  margin: 0 10px;

  #ap-handle {
    background: $white;
    height: 4px;
  }

  #ap-handle-circle {
    width: 13px;
    height: 13px;
    border-radius: 50%;
    background: $white;
    transform: scale(0.25);
  }
}   
}

ap-handle - это индикатор выполнения, который я пытаюсь использовать для заполнения временной шкалы во время воспроизведения песни.

1 Ответ

1 голос
/ 05 февраля 2020

Я не очень отзывчивый человек, так что извините за плохую практику:

#progress-bar {
  height: 20px;
  background: red;
  transform: scaleX(0);
  transform-origin: center left;
}
class App extends Component {
  constructor() {
    super();
    this.interval = null; // setInterval
    this.audioEl = new Audio(
      "https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3"
    );

    this.audioEl.addEventListener("canplaythrough", () => {
      this.setState({
        duration: this.audioEl.duration
      });
    });

    this.state = {
      currentTime: 0,
      duration: 0
    };
  }

  playAudio() {
    this.audioEl.play();
    // requestAnimationFrame would probably be better, but 
    // for example sake we'll use setInterval
    this.interval = setInterval(() => {
      this.setState({
        currentTime: this.audioEl.currentTime,
        progress: Math.ceil((this.audioEl.currentTime / this.audioEl.duration) * 100) / 100

      });
    }, 100);
  }

  stopAudio() {
    clearInterval(this.interval);
    this.audioEl.pause();
  }

  render() {
    return (
      <div>
        <button onClick={() => this.playAudio()}>Play</button>
        <button onClick={() => this.stopAudio()}>Stop</button>

        <div
          style={{ transform: `scaleX(${this.state.progress})` }}
          id="progress-bar"
        />
      </div>
    );
  }
}

Блиц

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...