leoasis / react-sound Goto Github PK
View Code? Open in Web Editor NEWSound component to play audio in your web apps
License: ISC License
Sound component to play audio in your web apps
License: ISC License
In your source code for v0.8.0 you have the onLoad
prop.
However, in my node_modules/lib/index.js
, this onLoad
prop does not appear. Something probably went wrong during your build and publish phase.
Hi
I assumed this would work on mobile ... did i assume wrong?
thanks
there is a lag on mobile devices , on desktop the audio plays without any noticeable lag.
Any chance of there being a mute property that's independent of the volume setting? Right now I have to use external state to remember the last volume setting and then set the actual volume to zero in order to mute. This adds overhead and a bit of complexity when displaying volume controls. It'd be great if react-sound took care of handling mute internally. I presume mute is a common enough feature.
I am making a notifications component and I want to play a short sound when the notification appears. Every notification component contains Sound
component inside with play status set to playing.
<Wrapper>
<Notification/>
<Notification/>
<Notification/>
</Wrapper>
expected behavior:
when notification is added, the sound is rendered, played to the end and stopped
real behavior:
the sound is played not only when notification is rendered, but also every time parent component is updated. Ex: another notification is removed or added.
How can I implement the "play once and shut up" behavior here? I don't want to move sound handling to the parent component because I want the sounds to overlap when a bunch of notifications appears in a short period of time. Thanks in advance
Hi,
i am creating an App with React/Meteor.
I installed react-sound and it works fine, when I take an Url from the Internet, for example those from the example.
But actually, I wanted to play music, stored in a local directory. I tryed many diffrent absoulute and relative paths, but I always get this error:
sound0: Failed to load / invalid sound? Zero-length duration reported.
Is it event possible to play music from local directory or do i have to consider any special things?
Thanks
Hi
While a sound plays and the url
of Sound
property is changed by updating states, the audio stops and doesn't play anymore. Any workaround for this?
An example is updating the url
using a html text box while the sound is playing.
hi
I'm trying to keep track of audio position, I'm using onPlaying event .
my code so far 👍
<Sound
url={this.state.songURL}
playStatus={this.state.playingStatus}
onLoading={this.handleSongLoading}
onPlaying={(audio) => this.handleSongPlaying(audio)}
playFromPosition={300}
onFinishedPlaying={this.handleSongFinishedPlaying}
/>
handleSongPlaying = (audio) => {
console.log(audio,'d')
let elapsed = this.formatMilliseconds(audio.position)
let total = this.formatMilliseconds(audio.duration)
let position = audio.position / audio.duration
console.log(elapsed,total,position)
this.setState({
elapsed: elapsed,
total: total,
position:position
})
}
calling setState results in infinite loop I'm not sure why . audio keeps playing in same position over and over .
Is there a way to make audio loop?
I am thinking using onPlaying prop to check current position and set it something close to 0 when audio is about to end, but I just wanted to ask if there is an easier way.
I am using this module to load dynamic audio. But even if the source changed, I am always getting the audio of the the first source,
Please find the code below
``` <Sound
url={text.audioContent} //this source is dynamic
ref={(element) => { this.rap = element; }}
playStatus={Sound.status.PLAYING}
/> ```
Hi,
When i try to install react-sound 1.0.0 version or higher, am getting uncaught range error:maximum call stack size exceeded"
What might be the reason for it.
Also, am unable to play songs in safari as well as iphones and ipad.
Is it possible to create a method to stop playback of all sounds?
Hi, great component indeed, thanks to you!
I was wondering if it's possible to play the sound multiple times, let's say if I click on my button playing the sound multiple times in quick succession?
From the soundmanager2 demo site, http://www.schillmania.com/projects/soundmanager2/demo/api/
it seems to be the default behaviour?
However from my app, the sound won't play again until it has completed playing.
Any idea how to achieve this? Thanks! :)
Hey Leonardo,
peerDependencies for React is specified as ^16.0.0-0
, so it only allows pre-release versions. Can we change that?
Thanks!
I have samsung s7 edge and on chrome. Works great on pc
Hello, is there any way to control the volume?
Can I turn off the console log of soundManager?
I'm upgrading from 0.9.0
and I'm unable to do a production build anymore with 1.0.0
.
I was doing the fix in issue #13 before in 0.9.0
, , but I took out that resolve from my production webpack file. Building production for 1.0.0
still doesn't work.
How can I get multiple sound components to work?
This is a great library, but automatically playing a sound doesn't seem to work on mobile due to an issue with permissions.
Rendering a basic Sound component works on PC (Chrome), but doesn't work on Android (Chrome). The error
Uncaught (in promise) DOMException: play() can only be initiated by a user gesture.
Full console output
sound4: Merged options: Object
sound4: play(): Attempting to load
sound4: load (soundfile.mp3)
Uncaught (in promise) DOMException: play() can only be initiated by a user gesture.
sound4: loadstart
sound4: suspend
sound4: durationchange (1410.612)
sound4: loadedmetadata
sound4: loadeddata
sound4: canplay
sound4: onload()
So when I build production on 0.9.0
, 0.10.0
, everything is fine. But when I build production on 1.0.0
, the sound has this weird clicking noise. I'm on React ^15.4.1
.
webpack.prod.js
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const InlineEnviromentVariablesPlugin = require('inline-environment-variables-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const nodeExternals = require('webpack-node-externals');
const {
commonRules: commonRulesBase,
resolveModules,
publicPath,
postcssConfig
} = require('./common.config');
const dotenv = require('dotenv');
dotenv.config();
const assetsPath = path.join(__dirname, '..', 'dist', 'public', 'assets');
const commonRules = [
...commonRulesBase,
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]___[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: { plugins: postcssConfig }
}
]
}),
include: [path.join(__dirname, '..', 'app')],
exclude: [path.join(__dirname, '..', 'node_modules')]
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
}),
include: [path.join(__dirname, '..', 'node_modules')],
exclude: [path.join(__dirname, '..', 'app')]
}
];
module.exports = [
{
name: 'client',
devtool: 'source-map',
context: path.join(__dirname, '..', 'app'),
entry: ['babel-polyfill', './client'],
output: {
path: assetsPath,
filename: 'bundle.js',
publicPath
},
module: {
loaders: commonRules
},
plugins: [
new ExtractTextPlugin({
filename: 'styles/main.css',
allChunks: true
}),
new InlineEnviromentVariablesPlugin(['NODE_ENV']),
new Dotenv()
],
resolve: {
modules: resolveModules
}
},
{
name: 'SSR',
context: path.join(__dirname, '..', 'app'),
entry: './SSR',
target: 'node',
output: {
path: assetsPath,
filename: 'SSR.js',
publicPath,
libraryTarget: 'commonjs2'
},
module: {
loaders: commonRules
},
externals: nodeExternals({
whitelist: [/\.(?!(?:jsx?|json)$).{1,5}$/i]
}),
plugins: [
new ExtractTextPlugin({
filename: 'styles/main.css',
allChunks: true
}),
],
resolve: {
modules: resolveModules
}
}
];
How to stop logs in console?
I am trying to control the volume of react-sound but, it looks alike volume props is not being accepted by component. here is the same code which I wrote and your NPM props.
My code:
this.state = {
volume: 10
}
<Sound
url={this.prepareUrl(this.state.track.stream_url)}
playStatus={this.state.playStatus}
onPlaying={this.handleSongPlaying.bind(this)}
playFromPosition={this.state.playFromPosition}
volume={this.state.volume}
onPause={() => console.log('Paused')}
onResume={() => console.log('Resumed')}
onStop={() => console.log('Stopped')}
onFinishedPlaying={this.handleSongFinished.bind(this)}/>
<Player
onVolumeUp={() => this.setState({volume: volume >= 100 ? volume : volume+10})}
onVolumeDown={() => this.setState({volume: volume <= 0 ? volume : volume-10})}
/>
Evan these log is not working.
Some props from your NPM :
{
key: 'propTypes',
value: {
url: _react.PropTypes.string.isRequired,
playStatus: _react.PropTypes.oneOf(Object.keys(playStatuses)).isRequired,
position: _react.PropTypes.number,
playFromPosition: _react.PropTypes.number,
onLoading: _react.PropTypes.func,
onPlaying: _react.PropTypes.func,
onFinishedPlaying: _react.PropTypes.func
},
enumerable: true
}, {
key: 'defaultProps',
value: {
playFromPosition: 0,
onLoading: noop,
onPlaying: noop,
onFinishedPlaying: noop
},
enumerable: true
}
can you please help me to understand this why I am not able to control the sound. am I missing something or something else?
It is showing me a ReferenceError:window is not defined in node_modules/soundmanager2/script/soundmanager2.js !!
How can we use soundmanager2 for server rendered scripts on node.On webpack it's working fine bcoz the browser can recognise window object.
Hi
I don't know how to get the progress in the mobile, when resource is loading like this , this is console log i can't find listener or params to get them . could you help me how can i get them , thank you
soundmanager2.js:1307 sound0: progress, 24% loaded 13:44:39.312 soundmanager2.js:1307 sound0: progress, 25% loaded 13:44:39.662 soundmanager2.js:1307 sound0: progress, 27% loaded 13:44:40.012 soundmanager2.js:1307 sound0: progress, 30% loaded 13:44:40.363 soundmanager2.js:1307 sound0: progress, 33% loaded 13:44:40.711 soundmanager2.js:1307 sound0: progress, 35% loaded 13:44:41.062 soundmanager2.js:1307 sound0: progress, 36% loaded 13:44:41.412 soundmanager2.js:1307 sound0: progress, 39% loaded 13:44:41.735 soundmanager2.js:1307 sound0: progress, 100% loaded
Hello! I'm using this package and noted then it not works on mobile phone (android) and on iPad. Quite strange - because my code is very simple and works on the desktop.
Any idea?
hi, sometimes not play sound, can you add mute or other property then I can use.
I want to play a sound in WebView (Android device), but it's not working, please help~, thanks~
How do you turn it off?
SoundManager V2.97a.20170601 (HTML5-only mode)
soundmanager2.js:1305 SoundManager 2 HTML5 support: mp3 = true, mp4 = true, ogg = true, opus = true, wav = true, flac = true
soundmanager2.js:1305 SoundManager 2: Ready. ✓
soundmanager2.js:1305 soundManager.createSound(): sound0 (https://raw.githubusercontent.com/scottschiller/SoundManager2/master/demo/_mp3/click-high.mp3)
soundmanager2.js:1303 sound0: Merged options: {url: "https://raw.githubusercontent.com/scottschiller/SoundManager2/master/demo/_mp3/click-high.mp3", autoLoad: true, volume: 100, position: 0, whileloading: ƒ, …}
soundmanager2.js:1307 sound0: load (https://raw.githubusercontent.com/scottschiller/SoundManager2/master/demo/_mp3/click-high.mp3)
soundmanager2.js:1307 sound0: load (https://raw.githubusercontent.com/scottschiller/SoundManager2/master/demo/_mp3/click-high.mp3)
Hello @leoasis,
Updating component with status PLAYING when previous status also is PLAYING causes no playing at all.
Problem with this condition:
if (this.props.playStatus === playStatuses.PLAYING) {
if (prevProps.playStatus === playStatuses.STOPPED) {
sound.play();
} else if (prevProps.playStatus === playStatuses.PAUSED) {
sound.resume();
}
//if prevProps.playStatus is PLAYING nothing happens...
}
Is this right behavior? If not, I can make a PR to fix this.
I open the page with the player on Android 4 via WebView, in
"onPlaying" returns the "duration" as 0.
On newer devices, everything is fine.
Hi! Excellent library that you have made! However, the amount of stuff getting console.log is humongous!
Is there anyway to remove it? It's coming from soundmanger2.js.
Hi
I'm using this module in my music player to great effect, really fantastic component.
I was wondering how hard would it be to add support for streaming from Readable streams instead of urls? I want to stream from a website that only returns an audio file if a particular header is passed, but I can't pass this header to react-sound, so I open the stream myself and would like to play that stream. The only solution for now is saving the stream locally in a temporary file and passing that to react-sound which is far from ideal.
Is it possible to add support for Readable streams?
Thanks
There are Gaps between loops when "loop=true"
I want to change the playback rate, but i can not call this.setState of a playback value because this will call render method and start the sound again.
As you can se https://jsbin.com/UGIxoJis/1/edit?html,output you can modify the playbackRate while a media is being played.
How can I access to the current sound element to modify his playbackRate?
I am currently using React 16.7.0 in my current project and I am getting the error mentioned above when trying to add this to my project. Any idea why this would be happening? Thanks!
I have a use for a callback that fires once after the stream is successfully loaded right before it begins to play. Would you accept a PR with this callback added as a prop?
Hi, great work on this project, thanks!
I was curious, is it possible to access the underlying soundmanager2 instance?
The reason I ask is that I'm hoping to be able to access Audio elements to attach to a Web Audio audioContext for visualization purposes.
Thanks again for all your work on this project.
Thank you for the great component, does its job really well.
I was trying to specify the url parameter in multiple formats as mentioned in
http://www.schillmania.com/projects/soundmanager2/doc/#smsound-url and unfortunately failed to do that.
My first guess was updating the propTypes in the source code. So on the line 246 instead of
url: _propTypes2.default.string.isRequired,
I put
url: _propTypes2.default.oneOfType([
_propTypes2.default.string,
_propTypes2.default.array
]).isRequired,
The test showed that the code, in fact, does not seem to cope with the multiple formats. I was trying ogg and wav like so <Sound url={["blah01.ogg", "blah01.wav"]} />
and it worked for the first file in the array. Then I renamed the first file on the server and the second wasn't loaded.
Could you please help me making it work.
A "looping" status would be nice. Right now, to loop, I have to make React re-render the component over and over again. It seems more complicated than necessary.
I'm trying to set url for server as I do with ajax . eg) /foo/bar.html
But it doesn't seem to work.
In react-sound, soundmanger will initialize when the DOM is ready. However, for my project, react-sound will be injected after DOM is ready. Thus, soundManager.createSound is not working when react-sound componentDidMount.
I found that soundmanger will provide beginDelayedInit
. Can we make use of it?
https://github.com/scottschiller/SoundManager2/blob/master/script/soundmanager2.js#L6271
Problem:
I'm using react-sound to play certain sounds at certain intervals for a game I'm creating. It all works excellently on most browsers, except Safari 11. Every time I try and play a sound on that browser specifically, I get this error:
Unhandled Rejection (NotAllowedError): The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
Source
I'm fairly confident it's because it's getting caught on the new autoplay restrictions from apple: Auto-Play Policy Change.
Request
The sound isn't super vital to the game, so is there a way to just catch this error, and prevent the sound from playing instead of crashing the app? Some callback I can handle myself in the case of an error?
Replicate Error
Autoplaying a sound on Safari 11 using react-sound. Can make a small repo replicating this problem if need be.
Is it possible to create a method to fade in/out the volume when start playing, as well as stop/pausing the audio clip?
Many thanks!
I upgraded from [email protected] to [email protected] (I'm also on [email protected]), and now I'm experiencing this issue. I've got a simplified Sound component in MyComponent's render()
like this...
<Sound url={audio.url} playStatus={Sound.status.PLAYING} playFromPosition={0} />
But every time it re-renders due to MyComponent receiving new props, the audio jumps to whatever value playFromPosition
has. My understanding is this is only suppose to happen when playFromPosition
changes, and as you can see, the value is static (just to test this). I've also made sure that MyComponent is not unmounting and remounting, as well as making sure the audio file is not reloading/remounting/changing.
For an immediate workaround I'll probably move to a controlled component using the position
prop, but I would love to just use playFromPosition
instead.
I'd be shocked if this was an issue for everyone due to a recent release, so perhaps I'm missing something obvious?
Any chance we can get this library updated to support react 16?
If you render the Sound component with an initial prop of playFromPosition or position set to anything, the sound will play from the beginning instead of the specified time. The song has to load up to that timestamp before playing or it will just default to the beginning.
Hello
I don't know if this is the right place to ask that but i tried to use react-sound in order to play an audio file generated from a node server but that don't work. I can see following error message from react log
soundManager.createSound(): sound0 (../audio/res2.wav)
soundmanager2.js:1303 sound0: Merged options: {url: "../audio/res2.wav", autoLoad: false, volume: 100, position: 0, whileloading: ƒ, …}
soundmanager2.js:1307 sound0: play(): Attempting to load
soundmanager2.js:1307 sound0: load (../audio/res2.wav)
soundmanager2.js:1307 sound0: waiting
soundmanager2.js:1307 sound0: loadstart
:3000/audio/res2.wav:1 GET http://localhost:3000/audio/res2.wav net::ERR_ABORTED
soundmanager2.js:1307 sound0: suspend
soundmanager2.js:1307 sound0: HTML5 error, code 4 (MEDIA_ERR_SRC_NOT_SUPPORTED)
soundmanager2.js:1305 sound0: Failed to load / invalid sound? Zero-length duration reported. (../audio/res2.wav)
SoundManager._writeDebug @ soundmanager2.js:1305
SMSound._onload @ soundmanager2.js:3219
(anonymous) @ soundmanager2.js:3994
(anonymous) @ soundmanager2.js:3885
localhost/:1 Uncaught (in promise) DOMException: Failed to load because no supported source was found.
Promise (async)
SMSound.play @ soundmanager2.js:2129
(anonymous) @ index.js:85
(anonymous) @ index.js:183
_createSound @ index.js:41
createSound @ index.js:158
componentDidMount @ index.js:83
(anonymous) @ ReactCompositeComponent.js:265
measureLifeCyclePerf @ ReactCompositeComponent.js:75
(anonymous) @ ReactCompositeComponent.js:264
notifyAll @ CallbackQueue.js:76
close @ ReactReconcileTransaction.js:80
closeAll @ Transaction.js:206
perform @ Transaction.js:153
perform @ Transaction.js:140
perform @ ReactUpdates.js:89
flushBatchedUpdates @ ReactUpdates.js:172
closeAll @ Transaction.js:206
perform @ Transaction.js:153
batchedUpdates @ ReactDefaultBatchingStrategy.js:62
enqueueUpdate @ ReactUpdates.js:200
enqueueUpdate @ ReactUpdateQueue.js:24
enqueueSetState @ ReactUpdateQueue.js:219
ReactComponent.setState @ ReactComponent.js:63
(anonymous) @ App.js:1058
Promise resolved (async)
sendMessage @ App.js:1056
onInputKeyUp @ App.js:1042
onKeyUp @ App.js:992
ReactErrorUtils.invokeGuardedCallback @ ReactErrorUtils.js:69
executeDispatch @ EventPluginUtils.js:85
executeDispatchesInOrder @ EventPluginUtils.js:108
executeDispatchesAndRelease @ EventPluginHub.js:43
executeDispatchesAndReleaseTopLevel @ EventPluginHub.js:54
forEachAccumulated @ forEachAccumulated.js:24
processEventQueue @ EventPluginHub.js:257
runEventQueueInBatch @ ReactEventEmitterMixin.js:17
handleTopLevel @ ReactEventEmitterMixin.js:28
handleTopLevelImpl @ ReactEventListener.js:72
perform @ Transaction.js:140
batchedUpdates @ ReactDefaultBatchingStrategy.js:62
batchedUpdates @ ReactUpdates.js:97
dispatchEvent @ ReactEventListener.js:147
Can you help me to understant what i'm missing ?
regards
sdeseille
npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react@^0.13.3
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.