Playing a sound on keypress using React - reactjs

I am not experienced in React so please excuse if this question will seem silly.
I have been trying to play a sound when a key is pressed on the keyboard.
I wanted to use the following solution:
https://www.npmjs.com/package/react-sampler/v/1.0.2
The problem is that when I try to play my sample i get an error:
Uncaught (in promise) DOMException: Failed to load because no supported source was found.
import React from 'react';
import './App.css';
import Sampler from 'react-sampler';
var samples = [{
file: "samples/sample1.wav",
key: 'h', // First sample
startAt: 0.2 // delay in sec
},{
file: 'samples/sample2.wav',
key: 'o', // Second sample
startAt: 0.05
}];
var ReactSamplerExample = () => ({
handleSampleLaunch: function(sample){
var elm = document.querySelector('[data-key='+sample.key+']');
elm.classList.add('active');
setTimeout(() => { elm.classList.remove('active')}, 150);
},
render: function() {
return (
<div>
<ul className="keys">
<li data-key="h">
<span className="key"></span><span className="sample">Sample 1</span></li>
<li data-key="o">
<span className="key"></span><span className="sample">Sample 2</span></li>
</ul>
<Sampler samples={samples} onLaunchSample={this.handleSampleLaunch} disabled={false} />
</div>
);
}
});
I checked the path to the files and they seem to be ok (all files are located in the same directory as the samples folder).
I'm not sure how to solve this. If there is a better tool or a simple audio API anyone can recommend or should switch to I would gladly take some advice.
Thanks in advance!

You are using react sampler for that. I like to use native html component with some customization for this situation.
Here my sample for you, hope i can help you with this sample:
Codesandbox Audio Play

Related

React phaser Reinitialize problem because of grid-engine plugin

I use "phaser", 'ion-phaser' and a phaser plugin 'grid-engine' for integrate a phaser game to react.
I can initialize the game successfully, then destroy it without an error. But when I try to reinitialize it İt give 2 errors
Scene Plugin key in use: GridEngine
and
Uncaught TypeError: Cannot read properties of undefined (reading 'create')
at Scene.create (isometric.js:93:1)
at SceneManager.create (phaser.js:84684:1)
at SceneManager.loadComplete (phaser.js:84615:1)
at LoaderPlugin.emit (phaser.js:1671:1)
at LoaderPlugin.loadComplete (phaser.js:165337:1)
at LoaderPlugin.fileProcessComplete (phaser.js:165311:1)
at SpriteSheetFile.onProcessComplete (phaser.js:4290:1)
at data.onload (phaser.js:16548:1)
second error at this line
this.gridEngine.create(cloudCityTilemap, gridEngineConfig);
Additionally when I try a phaser game without plugins like grid engine, there is not an error.
I search and I think I must remove grid-engine plugin when destroy game but I could not find how.
My question is
How to destroy a phaser game with included plugins and restart it?
this is code sample
const game = {
width: 800,
height: 600,
type: Phaser.AUTO,
scene: {
preload,
create,
update,
},
plugins: {
scene: [
{
key: 'GridEngine',
plugin: GridEngine,
mapping: 'gridEngine'
},
],
},
}
const gameRef = useRef(null)
const [initialize, setInitialize] = useState(false)
const destroy = () => {
if (gameRef.current) {
gameRef.current.destroy()
}
setInitialize(false)
}
return (
<>
<IonPhaser game={game} ref={gameRef} initialize={initialize} />
<button onClick={()=>setInitialize(true)}>Initialize</button>
<button onClick={destroy}>Destroy</button>
</>
)
}
Finally I want to change different games or levels at the same page
Im not 100% sure, if this will solve all your problems, but
<button onClick={setInitialize(true)}>
is not correct, you should not call the function, you should only pass it.
Try replacing that line with
<button onClick={ () => setInitialize(true)}>
For Details, checkout this article / documentation for details.
Update: How to get the game object
to get the Phaser Game object you would have to use getInstance (link to ion-phaser documentation) and to remove the Plugin you would have to do something like this:
this.gameRef.current.getInstance()
.then(game => game.plugins.removeScenePlugin("GridEngine"))

Unable to resolve an image in an array in React JS

I'm attempting to import images into an array in React JS. My intention is to be able to map through the array and have the images appear one as a time. However, my images are not being properly resolved. I'm fairly certain it is a syntax error of my doing, but I'm just not able to solve this. I'm currently a student who is just learning react, so any and all help is much appreciated!
import universe from "./images/universespider.jpeg"
let content = [
{
title: "Universe",
image: universe,
author: "Alex",
date: "09/09/8099",
blog: "Spider-Man is in different universes.",
},
]
import "./blogs.css"
import content from "../../content"
export default function blogs() {
return (
content.map((blog, i) => (
<div key={i}>
<div className="blogBox">
{blog.title}
{blog.image}
{blog.author}
{blog.date}
{blog.blog}
</div>
</div>
)
))
}
Error Message
You can't use imported images directly, in your case you should use element and pass your image as a source.
Instead of
{blog.image}
try this
import universe from "./images/universespider.jpeg"
...
<img src={universe} alt="universe"/>
More information about this assuming that your app was created with CRA.

Facebook Video Embed API allowfullscreen=false doesn't work which makes .play() function throw error

I am trying to embed facebook video on my mobile site and used their Video API documented here to do it.
I have initialised the video player as described and created Play & Pause buttons to control the video but when I use the Play button I get the error Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.
I have tried making data-allowfullscreen="false"
but that doesn't seem to work as the iframe that is loaded contains allowfullscreen="true"
Look at the image below, my has it false but the loaded iframe has it as true
Loaded iframe has allowfullscree=true even though I gave false in
I am using React and made a simple component for this
import React, { Component } from 'react';
import { Container, Button } from 'react-bootstrap';
class Vidtest extends Component {
handlePlayVideo = () => {
window.my_video_player.play();
}
handlePauseVideo = () => {
window.my_video_player.pause();
}
render() {
return(
<React.Fragment>
<div style={{position:"relative", width:"100%"}}>
<div id="video_div"
className="fb-video"
data-href="https://www.facebook.com/facebook/videos/10153231379946729/"
data-width="500"
data-allowFullScreen="false"
>
</div>
<Button className="btn btn-primary" onClick={this.handlePlayVideo}>Play Video</Button>
<Button className="btn btn-primary" onClick={this.handlePauseVideo}>Pause Video</Button>
</div>
</React.Fragment>
);
}
}
export default Vidtest
and have initialized FB video player in my index.html
<div id="root"></div>
let my_video_player
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '{my-app-id}',
xfbml : false,
version : 'v7.0'
});
// Get Embedded Video Player API Instance
FB.Event.subscribe('xfbml.ready', function(msg) {
if (msg.type === 'video') {
my_video_player = msg.instance;
console.log(msg.id);
console.log('my_video_player created lfakjd');
}
});
};
</script>
<script
async
defer
crossorigin="anonymous"
src="https://connect.facebook.net/en_GB/sdk/debug.js#xfbml=1&version=v7.0&appId={my-app-id}&autoLogAppEvents=1">
</script>
Can someone please help me resolve the issue here.?
I want to play the video using my_video_player.play() and not allow it to play in fullscreen.
Facebook definitely seems to be doing something different based on the device type (you can test this by using chrome dev tools - device toolbar - and switching between Mobile (no touch) and Desktop device types. The embedded player looks different between the two versions, and the mobile one seems to call requestfullscreen no matter whether the data-allowfullscreen was on or off. As near as I can tell, the only thing that that data-allowfullscreen seems to influence is on desktop, where there is a fullscreen button on the bottom of the video that shows or hides based on that flag.
Facebook embedded videos has a very frustrating and buggy api. They need to catch up with Youtube and Vimeo players.

draft-js-export-html not includes video when export

Currently, I'm using draft js editor, add plugin draft-js-video-plugin to insert video into editor and use draft-js-export-html to export html but the htmk result not includes video tag or anythings else.
Console log stateToHTML(this.state.editorState.getCurrentContent())
<p><br></p>
<figure> </figure>
<p><br></p>
I found same issue with export image here and they've resolved but not for video.
I've read their source code on github and seem now they only support text, link and image.
So how can I get result HTML includes video from draft js? Please help me, thank you guys.
Credit to rafaelespinoza https://github.com/sstur/draft-js-utils/issues/59#issuecomment-314527096
I'm able to fix it using `entityStyleFn like below:
entityStyleFn: (entity) => {
const entityType = entity.get('type').toLowerCase();
if (entityType === 'draft-js-video-plugin-video') {
const data = entity.getData();
return {
element: 'video',
attributes: {
src: data.src,
},
};
}
return null;
},

How can I change a source of a video in react?

I have used a react-video component in my reactjs web application and it's working with a default source link, but when I'm using my video as a source, nothing happens.
I have searched a lot, read the documentation about react-video component, but could not solve the problem.
import {Player} from 'video-react';
<div className = 'video-container'>
<Player
playsInline
fluid={false}
src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4"
width={600}
height={300}/>
</div>
I expect the new source to be working without any issues, but it never starts playing.
#Dato.Beriashvili, I have faced similar issues in default html video API, whenever i change src by anymeans video was not updated. so i have done below which fixed my issue.
useEffect(() => {
const myVideo= innerDoc.querySelector('#videoPlayer');
const mySource = innerDoc.querySelector('#source');
if (mySource && myVideo) {
mySource.setAttribute('src', videoUrl);
myVideo.load();
}
}, [videoUrl]);
whenever url changed, i'm manually loading it.

Resources