【问题标题】:How can I make a song progress bar for my audio player?如何为我的音频播放器制作歌曲进度条?
【发布时间】:2020-02-05 06:17:42
【问题描述】:

我制作了一个简单的音频播放器,但现在我想添加一个歌曲进度条,在歌曲播放时填满时间线,这是我的 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 是我试图在歌曲播放时用来填充时间线的进度条。

【问题讨论】:

  • 您是否将歌曲的长度存储在任何地方?
  • 是的!它处于状态,可以通过我的组件中的this.state.duration 访问(这也是它呈现html的地方)
  • 您需要获取歌曲的当前时间、持续时间,并将其标准化为 0-100% 并将其应用于进度条。
  • @Phix 有道理,你能提供一个例子吗?作为参考,我可以通过this.state.currentTime 访问歌曲的当前时间,通过this.state.duration 访问歌曲的持续时间。我猜你会找到某种比率(currentTime 与歌曲持续时间的百分比)。我不确定如何在 CSS 中使用它:(
  • 我的componentDidMount 函数中确实有这个比率,这似乎与您所说的接近:let ratio = this.audio.currentTime / this.audio.duration;

标签: html css


【解决方案1】:

我不是一个反应灵敏的人,所以请原谅这里的任何不良做法:

#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>
    );
  }
}

Blitz

【讨论】:

  • 谢谢!我试试看!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
相关资源
最近更新 更多