Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get audio element?

Using React, I wish to get the audio element.

var AudioPlayer = React.createClass({
    componentDidMount: function () {
        console.info('Audio: component did mount');
        var audio = React.findDOMNode('audio');
        console.info('audio', audio);
    },
    render : function() {
        return (
            <audio src="/static/music/foo.mp3" controls />
        );
    }
});

But I keep receiving the error:

Error: Invariant Violation: Element appears to be neither ReactComponent nor DOMNode (keys: 0,1,2,3,4)

Surely lowered components are React classes?

like image 923
Tjorriemorrie Avatar asked Jul 27 '15 15:07

Tjorriemorrie


People also ask

How do I get audio in HTML?

HTML Audio - How It WorksThe controls attribute adds audio controls, like play, pause, and volume. The <source> element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.

How do I get audio in Javascript?

Audio play() Method The play() method starts playing the current audio. Tip: This method is often used together with the pause() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).

Where does the audio tag go in HTML?

To answer the question correctly, regardless of whether or not you want to display the Audio element, it should go in the body tag. If you don't put it in the body tag, Chrome, for example, will move it there anyways. So yes, if you want it to be visible put it in the body tag and make sure it is where you want it.

What HTML element is used for playing audio files?

The <audio> HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream .


1 Answers

It works using the component references:

var AudioPlayer = React.createClass({
    componentDidMount: function () {
        console.info('[AudioPlayer] componentDidMount...');
        this.props.el = React.findDOMNode(this.refs.audio_tag);
        console.info('audio prop set', this.props.el);
    },
    render: function() {
        console.info('[AudioPlayer] render...');
        return (
            <audio ref="audio_tag" src="/static/music/foo.mp3" controls autoplay="true"/>
        );
    }
});
like image 187
Tjorriemorrie Avatar answered Sep 19 '22 16:09

Tjorriemorrie