【问题标题】:Why does my "Audio-Button" don`t play a sound (onClick)为什么我的“音频按钮”不播放声音(onClick)
【发布时间】:2019-04-19 18:30:42
【问题描述】:

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

【问题讨论】:

  • Playing sound in reactjs的可能重复
  • 嘿 Brune,这不是一份报告,而是一个友好的标签,以便您和其他人可以参考之前提出的与您的问题类似的问题。这就是 stackoverflow 的工作原理,希望您阅读指南?

标签: reactjs audio


【解决方案1】:

button.js 中的handleClick 方法返回一个&lt;audio&gt; 元素,这是多余的,因为您想播放声音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 保持原样。

这是一个有效的codesandbox

【讨论】:

  • 非常感谢。今晚我将检查解决方案,并报告一切是否良好:))))
  • 拜托,我已经附上了codeandbox,它在那里工作。
  • 感谢您的帮助,解决方案有效。我现在将了解我的解决方案出了什么问题。
  • 如果它适合您,请考虑支持/接受答案。 :)
  • 点赞!非常感谢你。你知道,我自己学习,有时很难找到自己的方式:)))
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 2012-02-02
  • 1970-01-01
相关资源
最近更新 更多