javascript-在React中管理多个音频源
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-在React中管理多个音频源,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2292字,纯文字阅读大概需要4分钟。
内容图文
我有一个React组件,当您单击按钮时可以播放/暂停音频.效果很好,我一次在页面上渲染了其中的5个.但是,如果您单击一个播放,然后单击另一个播放,则两个音频都在播放,这不是很好.这是我的组件代码:
import React from 'react';
import playIcon from './images/play.png';
import pauseIcon from './images/pause.png';
class Music extends React.Component {
constructor(props) {
super(props);
this.state = { 'play': false };
this.url = props.src;
this.audio = new Audio(this.url);
this.audio.preload = 'none';
this.togglePlay = this.togglePlay.bind(this);
}
togglePlay() {
this.setState({'play': !this.state.play}, () => {
this.state.play ? this.audio.play() : this.audio.pause();
});
}
componentWillUnmount () {
this.audio.pause();
}
render() {
return (
<div style={this.props.style} className={this.props.className}>
{this.state.play
? <button className="audio-button" aria-label="Pause" onClick={this.togglePlay}><img src={pauseIcon} width="34" height="34" alt="Pause"></img></button>
: <button className="audio-button" aria-label="Play" onClick={this.togglePlay}><img src={playIcon} width="34" height="34" alt="Play"></img></button>}
</div>
);
}
}
export default Music;
我已经做了一些环顾,一个潜在的解决方案是使用redux或其他状态管理库.我想避免这种情况,因为在此站点中我不需要这样做.我已经研究了事件侦听器(即solution proposed here),但是当我执行document.getElementsByTagName(‘audio’)时,我得到了一个空的HTMLCollection. This solution更近了,但我无法弥合jQuery中的实现与React中所使用的实现之间的差距.
有没有办法识别正在播放的音频并在播放新音频之前从React Component暂停它?任何和所有建议表示赞赏.
解决方法:
import React from 'react';
import audio1 from './audio1.mp3';
import audio2 from './audio2.mp3';
class AudioList extends React.Component {
constructor (props) {
super(props);
this.audios = props.list.map(audio => new Audio(audio));
}
getCurrentAudio () {
return this.audios.find(audio => false === audio.paused);
}
toggle (nextAudio) {
const currentAudio = this.getCurrentAudio();
if (currentAudio && currentAudio !== nextAudio) {
currentAudio.pause();
}
nextAudio.paused ? nextAudio.play() : nextAudio.pause();
}
render () {
return (
<div>
{ this.audios.map((audio, index) =>
<button onClick={() => this.toggle(audio) }>
PLAY AUDIO { index }
</button>
) }
</div>
)
}
}
export default () => <AudioList list={[ audio1, audio2 ]} />;
PS:新的Audio(url)返回HTMLAudioElement.
内容总结
以上是互联网集市为您收集整理的javascript-在React中管理多个音频源全部内容,希望文章能够帮你解决javascript-在React中管理多个音频源所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。