audio react.js code example
Example 1: play sound onload react
import React, { useState, useEffect } from "react";
const useAudio = url => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);
const toggle = () => setPlaying(!playing);
useEffect(() => {
playing ? audio.play() : audio.pause();
},
[playing]
);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, []);
return [playing, toggle];
};
const Player = ({ url }) => {
const [playing, toggle] = useAudio(url);
return (
<div>
<button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
</div>
);
};
export default Player;
Example 2: play audio in react
import ReactAudioPlayer from 'react-audio-player';
<ReactAudioPlayer
src="my_audio_file.ogg"
autoPlay
controls
/>
Example 3: play sound onload react
class Music extends React.Component {
state = {
play: false
}
audio = new Audio(this.props.url)
componentDidMount() {
audio.addEventListener('ended', () => this.setState({ play: false }));
}
componentWillUnmount() {
audio.removeEventListener('ended', () => this.setState({ play: false }));
}
togglePlay = () => {
this.setState({ play: !this.state.play }, () => {
this.state.play ? this.audio.play() : this.audio.pause();
});
}
render() {
return (
<div>
<button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
</div>
);
}
}
export default Music;
Example 4: react audio player
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
import ReactAudioPlayer from '../src/index.tsx';
describe('ReactAudioPlayer', function() {
const song = './fixtures/turkish_march.ogg';
test('renders an audio element', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer />
);
const instanceEl = ReactDOM.findDOMNode(instance);
expect(instanceEl.tagName).toBe('AUDIO');
});
test('sets the loop attribute if provided', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer
src={song}
loop
/>
);
const instanceEl = ReactDOM.findDOMNode(instance);
expect(instanceEl.getAttribute('loop')).not.toBe(null);
})
test('sets title', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer
src={song}
title="Turkish march"
/>
);
const instanceEl = ReactDOM.findDOMNode(instance);
expect(instanceEl.getAttribute("title")).toBe("Turkish march");
})
test('receives all custom props', function() {
const instance = ReactTestUtils.renderIntoDocument(
<ReactAudioPlayer
src={song}
name="custom-name"
data-id="custom-data"
controlsList="nodownload"
/>
);
const props = Object.keys(instance.props);
expect(props).toContain('name');
expect(props).toContain('data-id');
expect(props).toContain('controlsList');
});
});