Javascript audio onClick won't play - javascript

I was making an game from a course project using html, css and javascript, and in this game i need to kill a fly everytime i click on it, so i decided to use an audio for everytime the fly dies to make the game more fun, the rest of the function is ok but my audio is not playing, altough i'm getting the audio source right.
`
fly.addEventListener("click", function(){
this.remove()
points += 10
document.getElementById('hasPoints').innerHTML = points
console.log(sound)
sound.addEventListener("canplaythrough", function(){
sound.play()
})
})
`
i've also already tried to add the sound preload property to auto but it still didn't work

The only solution i could achieve was changing how the sound would function, instead from playing everytime i kill a fly, i made it play for every click on the window, using window.addEventListener

Related

How to play audio using JS efficiently and without delay

I am building a very simple JS code where I can play "organ" (like a piano) clicking on buttons just like if I were playing a piano, tapping in the keys. I recorded 10 samples of 10 notes of my organ and saved each separetly file as mp3.
Then I created 10 buttons, when I click each button the sampled sound of that note is played. The problem that I am facing, is that there is always a small delay (like 200 to 300 ms) between clicking the button and the sound actually playing.
You can try a simplified code below which reproduces the "bug" very easily below:
$(document).ready(function() {
temp = new Audio("https://quemfazsite.com.br/temp/teclado/tons/102.mp3");
$("#play").on(
"click",
function() {
temp.currentTime = 0;
temp.play();
}
);
$("#stop").on(
"click",
function() {
temp.pause();
}
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div id="play">PLAY</div>
<div id="stop">STOP</div>
I also tried using an <audio> HTML element but the same delay happens. In the past I found a website very similar with what I am trying to build right now, and it played the sounds very smoothly, fast... but I cant find it anymore.
Do you have any idea what I can do to remove the delay that I am facing? I tried this code on 2 different notebooks running Windows 10 and also on and Android phone (samsung note). The delay is not in the audio file, I created each audio file using Audacity and I made sure there is absolutely no empty space at the beginning of each mp3 track.
And there is one more problem: sometimes when I click the PLAY button, there is some small noise which lasts no more than probably 50ms, is very very fast noise, and it shows up randomly... This same exactly problem happened on the 3 devices I tested. Any suggestion I could try my friends?

Mute sound in P5JS while still using its waveform?

I am using the p5.sound library to create an audio visualiser. This works perfectly, however I would like to be able to keep this functionality without the song actually playing.
The waveform and spectrum are both based off of the volume, so setting that to zero means that the whole thing just displays no sound. Is there a way to mute the tab using javascript, or stop the noise from actually playing, just keep it being read by the .waveform and .analyse functions?
Code: https://www.openprocessing.org/sketch/523860#code
I faced the same need, and actually solved with no code, simply muting the tab in the browser.
--> To mute a browser tab in Firefox, right-click the tab and select “Mute Tab”

How to interact with Netflix Cadmium video player on the client?

I have a Netflix account and I have peeked under the hood at its video player running inside Google Chrome. Netflix calls its video player "Cadmium" and the javascript exposes all the functions and event handlers you might expect, such as play, stop, pause, mute, etc. I'm building a little Chrome extension that would enable me to call these Cadmium player function, but the hard part for me is figuring out how to create an instance of the player so I can start calling. The javascript is large, complex, and somewhat obscure. Once I can create an instance of that player, I'm thinking that making calls into the functions will be easy.
Here is a relevant chunk of js:
muteOn: function() {
this.savedVolume = this.getVolume(),
this.updateVolumeDisplay(0),
this.scrubber.updatePercent(0),
this.muted = !0,
this.videoPlayer.setMuted(this.muted)
}
In Chrome dev tools I can set a breakpoint inside that block, and execution hits the breakpoint when I click the Mute button on the netflix video player. The Netflix js is (unsurprisingly) heavily obfuscated via method renaming. I tried stepping through the code in the debugger and ended down a hundred rabbit holes, never able to find my way to the top of the stack, so that I could make that same call (at top of stack) to simulate the user clicking the mute button. I also tried the approach of programmatically clicking the mute button on the UI player, which would meet my needs equally well, but they have serious defensive mechanisms in there, spinning me like a top.
Since there are over 100K lines of javascript, and I'm uncertain which chunks exactly would be relevant for this post, I would like to suggest that you load Netflix in Chrome, open dev tools, play a movie, and inspect the pause or mute button. Interacting with those video player controls takes you into the maze of javascript which I'm trying to see how I can tap into to control aspects of the player programmatically (just from dev tools is fine for now). Another important thing I need to figure out is how to query the video player to determine the current elapsed time of the playing video.
Any ideas how I can crack this nut? (Thanks in advance!)
Using Chrome, I get playback using HTML 5 video.
Once you get a hold on the <video> tag element, you can use the HTML 5 video API:
Get the <video> element
var video = document.evaluate('//*[#id="70143639"]/video',document).iterateNext()
70143639 is the id of the video, as in https://www.netflix.com/watch/70143639
Remaining time (HH:mm)
document.evaluate('//*[#id="netflix-player"]/div[4]/section[1]/label', document).iterateNext().innerHTML
Elapsed time (seconds)
video.currentTime
Elapsed time updates
video.addEventListener("timeupdate",
function(e) {
console.debug("Seconds elapsed: ", e.timeStamp/1000/60);
}
);
Note that I don't get the same results as with video.currentTime, you may need to use an offset based on the difference. Also it may be something explained in the spec: https://www.w3.org/TR/html5/embedded-content-0.html
Play
video.play();
Pause
video.pause();
Go back and forth in time
Courtesy of rebelliard:
netflix.cadmium.UiEvents.events.resize[1].scope.events.drage‌​nd[1].handler(null, {value: 600, pointerEventData: {playing: false}}); where 600 is the number of seconds to seek.
Note that I ran into "Whoops, something went wrong..." using this:
video.currentTime += 60;
Even with pause and play calls. This is what this demo page does, you nay need to read the full spec on seeking.
Mute and get muted status
video.muted = true
Like video.currentTime, this is a writeable property.

How to increase audio loading speed using JavaScript?

I have created code for playing an .mp3 file using JavaScript. But the file is taking to much time to play on Android. I want to play the sound quickly after click on a text image. How do I increase loading speed on Android?
My JavaScript code:
if(window.audio)
{
audio.pause();
}
window.audio = new Audio (audio_path);
window.audio.play();
Check demo here -
http://97.74.195.122/gizmo-demo/canvasslidertwo.php
In the above link, click on the Japanese word for playing sound.
You are actually facing the bug depicted in this question. Which makes chrome browsers redownload the files from an Audio Element each time you change its src property (no-caching).
One solution would be to use the WebAudioAPIand store your audio files in the buffer. Doing so, you should be able to call them with no latency.
You can check the accepted answer for an example on how to deal with it.
Or you could also try not to call a new Audio() on each click, and rather load every audios from your page and only call their play() method on click.
But I'm not sure it would fix your issue.

HTML5 <video> callbacks?

I'm working on a site for a client and they're insistent on using HTML5's video tag as the delivery method for some of their video content. I currently have it up and running with a little help from http://videojs.com/ to handle the Internet Explorer Flash fallback.
One thing they've asked me to do is, after the videos finish playing (they're all a different length), fade them out and then fade a picture in place of the video --- think of it like a poster frame after the video.
Is this even possible? Can you get the timecode of a currently playing movie via Javascript or some other method? I know Flowplayer (http://flowplayer.org/demos/scripting/grow.html) has an onFinish function, is that the route I should take in lieu of the HTML5 video method? Does the fact that IE users will be getting a Flash player require two separate solutions?
Any input would be greatly appreciated. I'm currently using jQuery on the site, so I'd like to keep the solution in that realm if at all possible. Thanks!
You can view a complete list of events in the spec here.
For example:
$("video").bind("ended", function() {
alert("I'm done!");
});
You can bind to the event on the element like anything else in jQuery...as for your comment question, whatever element you're delivering for IE, yes, it would need a separate handler rigged up to whatever event it provides.
For the other question about timecode, the timeupdate event occurs when it's playing, and the durationchange event occurs when the overall duration changes. You can bind to and use them just like I showed with the ended event above. With timeupdate you'll probably want the currentTime property, with durationchange you'll want the duration property, each of which you get directly off the DOM object, like this:
$("video").bind("durationchange", function() {
alert("Current duration is: " + this.duration);
});
There is an OnEnded event associated with the video tag. However, it does not work for me in the current version of Google Chrome.
HTML 5 Video OnEnded Event not Firing
and see also
Detect when an HTML5 video finishes
For a general-purpose solution (supports video tag with fallback see)
http://camendesign.com/code/video_for_everybody
or
http://www.kaltura.org/project/HTML5_Video_Media_JavaScript_Library or http://www.mediafront.org/
I used this code. It basically reloads the video which will get the poster to show again. Assuming you want the image at the end to be the same as the poster. I only have one video on the page so using the video tag works. I have my video set to autoplay on page load so I added the pause after the reload.
<script type="text/javascript">
var video= $('video')[0];
var videoJ= $('video');
videoJ.on('ended',function(){
video.load();
video.pause();
});
</script>

Categories