为什么我的“音频按钮”不播放声音(onClick)

时间:2019-04-19 18:30:42

标签: reactjs audio

我正在努力找出为什么单击按钮时我的按钮不播放声音。 console.log()测试工作正常,但-part无效。我也尝试了一些npm-packets来解决此问题,但似乎我的代码有一个普遍的问题。它出什么问题了?有人可以帮我吗?

main.js:

import Button from './button';

class Drumpad extends Component {
  constructor(props) {
    super(props);
        this.state = { 
              Q:
              {
                id: 'Q',
                name: 'Q',
                src: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
              },
          }
    }
  render() {
    return (
      <div style={test}>
        <div id='row1'>
        <Button cfg={this.state.Q}/>
        </div>
      </div>
    )
  }
}

还有button.js:

class Button extends Component {
  constructor(props) {
    super(props);
    this.state = {
        }
      }
      handleClick = () => {
        console.log(this.props.cfg.src);
        return (
          <audio ref='audioClick' src={this.props.cfg.src} type='audio/mp3' autoPlay>
          );
        };
  render() {

    return (
      <div>
        <button style={buttonStyle} onClick={this.handleClick}>
            <h1>{this.props.cfg.name}</h1>
        </button>
      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:1)

handleClick中的button.js方法返回一个<audio>元素,这是多余的,因为您想播放声音onClick

相反,我使用Audio构造函数来创建音频剪辑的实例,使用作为道具提供的URL(我将其设置为状态)。

然后,我使用回调在其上调用play()方法。

  handleClick = () => {
    const audio = new Audio(this.props.cfg.src);
    this.setState({ audio }, () => {
      this.state.audio.play();
    });
  };

所以您的button.js会变成这样:

import React, { Component } from "react";

const buttonStyle = {};

export default class Button extends Component {
  constructor(props) {
    super(props);
    this.state = {
      audio: false
    };
  }

  handleClick = () => {
    console.log(this.props.cfg.src);
    const audio = new Audio(this.props.cfg.src);
    this.setState({ audio }, () => {
      this.state.audio.play();
    });
  };

  render() {
    return (
      <div>
        <button style={buttonStyle} onClick={this.handleClick}>
          <h1>{this.props.cfg.name}</h1>
        </button>
      </div>
    );
  }
}

您的main.js保持不变。

这里是工作中的codesandbox

相关问题