为了账号安全,请及时绑定邮箱和手机立即绑定

单击按钮时需要播放音频文件的帮助(React)

单击按钮时需要播放音频文件的帮助(React)

慕雪6442864 2023-12-04 19:23:25
这是我正在编写的代码。这是一个鼓机项目。我已成功创建按钮,我需要帮助来在单击按钮后播放音频文件。src 将填充音频文件的链接,我的项目告诉我将一个元素放入按钮元素内。这是代码: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 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

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


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>

此外,如果预加载音频文件,您可能会获得更好的用户体验:


const sounds = [

  {

    idnum: “1”,

    id: “Q”,

    src: “1.html”,

    audio: new Audio("1.html"),

  },

]

并使用这个处理程序:


soundOn = info => {

  info.audio.play();

}


查看完整回答
反对 回复 2023-12-04
  • 1 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信