首页 > 解决方案 > 为什么我的“音频按钮”不播放声音(onClick)

问题描述

我正在努力找出为什么当我单击它时我的按钮不发出声音。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>
    )
  }
}

标签: reactjsaudio

解决方案


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

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

然后我使用回调来调用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遗体保持原样。

这是一个有效的代码框


推荐阅读