在单击按钮时需要帮助播放音频文件(反应)

时间:2020-04-10 19:17:49

标签: javascript html reactjs

这是我正在处理的代码。这是用于鼓机项目的。我已经成功创建了按钮,并且在单击按钮后播放音频文件时需要帮助。 src将充满指向音频文件的链接,我的项目告诉我将一个元素放在button元素内。

这是代码:

import React from “react”;
import ReactDom from “react-dom”;

const sounds = [
{
idnum: “1”,
id: “Q”,
src: “1.html”,
},
{
idnum: “2”,
id: “W”,
src: “2.html”,
},
{
idnum: “3”,
id: “E”,
src: “3.html”,
},
{
idnum: “4”,
id: “A”,
src: “4.html”,
},
{
idnum: “5”,
id: “S”,
src: “5.html”,
},
{
idnum: “6”,
id: “D”,
src: “6.html”,
},
{
idnum: “7”,
id: “Z”,
src: “7.html”,
},
{
idnum: “8”,
id: “X”,
src: “8.html”,
},
{
idnum: “9”,
id: “C”,
src: “9.html”,
},
];

class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
audioSource: “not clicked”,
};
this.soundOn = this.soundOn.bind(this);
}
/* soundOn() {
return sounds.src.play();
} */

// I know the above method will not work. I just had it to check if my buttons were working.

render() {
const buttonData = sounds.map((info) => (
<button className=“drum-pad” id={info[“idnum”]} onClick={this.soundOn}>
{info[“id”]}
));
return buttonData;
}
}
export default Button;

任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

在单击处理程序时使用它:

soundOn = info => {
  var audio = new Audio(info.src);
  audio.play();
}

并将其放在onClick道具中:

<button
  // you need a key prop
  key={info.idnum}
  className=“drum-pad”
  id={info[“idnum”]}
  onClick={() => this.soundOn(info)}
>
  {info.id}
</button>

此外,如果预加载音频文件,可能会获得更好的UX:

const sounds = [
  {
    idnum: “1”,
    id: “Q”,
    src: “1.html”,
    audio: new Audio("1.html"),
  },
]

并使用此处理程序:

soundOn = info => {
  info.audio.play();
}