当另一个开始播放时暂停音频

时间:2021-04-15 20:41:24

标签: reactjs audio react-redux react-player

我在表格的每一行都有一个音频播放器。单击时,音频播放。这里的问题是用户可以通过单击每一行同时播放多个音频。如果正在播放音频并且用户单击另一行的音频,则正在播放的音频必须暂停,新选择的音频应开始播放。我试图在每一行更新 isPlaying 的状态,但无法实现我想要的。请让我知道如何使它工作。这是我迄今为止尝试过的:

Employee.js

class Employee extends Component<Props, State> {

  render() {
   const employees = this.props.employees;
   return(
    <div>
     <table>
      {employees && employees.map((emp, index) => this.renderEmp(emp, index))}
    </table>
   </div>
  );
}

renderEmp(emp, i) {
 emp.playing = false;
 return (
  <tr key={emp.id}>
    <td>
      <EmpPlayer emp={emp} employees={this.state.employees} key={i}/>
    </td>
  </tr>);
  }
 }

EmpPlayer.js

import React, { Component } from 'react';
import Sound from 'react-sound';
import { ProgressBar } from 'react-player-controls';

type Props = {
 emp: emp,
 employees: employees,
};

class EmpPlayer extends Component<Props, State> {
 toggle;

 constructor(props: Props) {
  super(props);
  this.state = {
   status: Sound.status.PAUSED,
   isPlaying: false
  };
  this.toggle = this.toggle.bind(this);
 }

 toggle() {
  this.setState({ isPlaying: !this.state.isPlaying }, () => {
   this.setPlayStatus();
  });

  if (this.state.status === Sound.status.PLAYING) {
   this.setState({ status: Sound.status.PAUSED, elapseTime: this.state.elapseTime });
  } else {
   this.setState({ status: Sound.status.PLAYING });
  }
}

setPlayStatus () {
 const {employees, emp} = this.props;
 emp.isPlaying = this.state.isPlaying;
 employees.forEach(e => e.playing = e.id === emp.id ? true : false);
}

render() {
 const { emp, employees } = this.props;
 return (
  <div>
    <div onClick={this.toggle}>
       {this.state.status === Sound.status.PLAYING ? (<Icon>pause</Icon>) : (<Icon>play</Icon>)}
    </div>
    <Sound
      url={emp.url}
      playStatus={emp.isPlaying ? this.state.status : Sound.status.PAUSED}
      autoLoad={true}
      onPlaying={this.onPlaying}
      onLoading={this.onLoading}
    />
    <ProgressBar/>
  </div>));
   }
  }

0 个答案:

没有答案