Javascript play audio when loaded - javascript

so I have a code for volume slider. What it does is that it plays sound when you have changed volume after loading the slider. For example if default value of the slider is 50 it wont play sound right after loading the audio file, you need to change value to higher or lower so sound can come out. So I need help with JavaScript. What can I do so it starts playing the sound whenever is loaded?
Full code : https://www.w3schools.com/code/tryit.asp?filename=FQZVZUX36JFD
JS:
$("#volume").slider({
min: 0,
max: 100,
value: 50,
range: "min",
slide: function(event, ui) {
setVolume(ui.value / 100);
}
});
var myMedia = document.createElement('audio');
$('#player').append(myMedia);
myMedia.id = "myMedia";
playAudio('http://listen.shoutcast.com/newfm64aac-', 0);
function playAudio(fileName, myVolume) {
myMedia.src = fileName;
myMedia.setAttribute('loop', 'loop');
setVolume(myVolume);
myMedia.play();
}
function setVolume(myVolume) {
var myMedia = document.getElementById('myMedia');
myMedia.volume = myVolume;
}

Google recently released a browser update that prevents initial playing or autoplaying of media elements (Note: not the solution for this answer, but a potential solution for similar cases.)

You're setting the initial volume to zero with this call:
playAudio('http://listen.shoutcast.com/newfm64aac-', 0);
To have it load at a default of 50 your call should be:
playAudio('http://listen.shoutcast.com/newfm64aac-', 50);

Related

MediaPipe Selfie Segmentation results are not invoking when moved to other Chrome tabs

const videoElement =document.getElementsByClassName('input_video')[0];
selfieSegmentationObj = new SelfieSegmentation({locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/#mediapipe/selfie_segmentation/${file}`;
}});
selfieSegmentationObj.setOptions({
modelSelection: 1,
selfieMode: false,
effect: 'mask',
});
selfieSegmentationObj.onResults(selfieSegmentationResults);
cameraObj = new Camera(videoElement, {
onFrame: async () => {
await selfieSegmentationObj.send({image: videoElement});
},
width: 1280,
height: 720
});
cameraObj.start();
function selfieSegmentationResults(results) {
const canvasElement = document.getElementsByClassName('output_canvas')[0];
var canvasCtx = canvasElement.getContext('2d');
canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
canvasCtx.save();
canvasCtx.drawImage(results.segmentationMask, 0, 0, canvasElement.width, canvasElement.height);
}
When we moved from one tab to another tab then callback function "selfieSegmentationResults" is not getting called from the SelfieSegmentation object.
Please, someone, help if there is any other solution that can get the segmented image data even if we moved to another Chrome tab.
Selfisegmentation might be using requestAnimationFrame under the hood which only works in the active tab.
The same thing was happening to me. I was building a background removing app with selfisegmentation and whenever I switched the tab, it stopped on the last frame. I solved it by using web workers.

howler.js play sound at a specific position

Hi I would like to start playing a sound on a scecific position. The api said that I can use .pos but it doesn't start where I would like it to start
<p>This sound last 13 sec.</p>
<h1>Audio</h1>
<h3>2:00</h3>
<h3>3:00</h3>
<h3>4:00</h3>
<h3>10:00</h3>
My javascript.
var son = [false, "0000"]
sound = new Howl({
urls: ['http://goldfirestudios.com/proj/howlerjs/sound.mp3'],
autoplay: false
});
function playSequence(events,valeur){
//if there is no sound play the track at a certain position
var playSound = function(valeur){
if(son[0] == true){
sound.stop();
son[0] = false;
}else{
son[0] = true;
sound.pos = parseInt(valeur[0]); // position at 2 sec
sound.play();
}
}
playSound(valeur);
}
//play the sound on click
$("a.val2").on('click', function(events){
valeur = $(this).text();
playSequence(events, valeur);
});
pos is a method, not a property. For best compatibility, you would want to play it like follows (fixed in the 2.0 beta branch):
sound.play(function(id){
sound.pos(valeur[0], id);
});
Here's how you would do it in 2.0 (check 2.0 branch at https://github.com/goldfire/howler.js):
var id = sound.play();
sound.seek(valeur[0], id);
If you are only playing one sound then there is no need to set the id, but it is best practice to change the position after playing when using 1.1.x.
I was having issues playing a sound at a specific time as well, it worked on the first play of a sound, but if I tried to go back and play that sound again, using seek immediately wouldn't work.
I just figured out a way to consistently make it work using howler v2:
function playSoundAtPosition(sound, pos) {
sound.once("play", () => {
sound.seek(pos);
});
sound.play();
}
This makes use of the callback method once which fires the callback to the play event and then immediately removes itself. I believe this helps because it waits until it actually knows the sound is playing before seeking to the desired time.
I know this is an old question but hopefully it's useful to someone if they come across this!
You can use Sprites!
var sound = new Howl({
src: ['sounds.webm', 'sounds.mp3'],
sprite: {
blast: [0, 3000],
laser: [4000, 1000],
winner: [6000, 5000]
}
});
// Shoot the laser!
sound.play('laser');
:)
I found it at this link How to Create and use Sprites

How to change playback rate in jwplayer

I want to change the playback speed of video in HTML5 mode of jwplayer. I am not interested in flash browser, we will be restricting this feature only for HTML5 browsers
Issue:
I tried changing the playbackrate for HTML5 in jwplayer but playbackrate is coming undefined
i am attaching my code below
jwplayer('my-video').setup({
sources: [
{file:'./test.mp4' , type: "mp4" },
],
width:'640px',
height:'360px',
image : './test.jpg'
});
$("#speed_10").click(function() {
myVid=$( "#my-video" ).find('.jwvideo').find('video');
alert(myVid.length);
alert($( "#my-video" ).find('.jwvideo').find('video').attr('src'))
alert(myVid.playbackRate)
alert($( "#my-video" ).find('.jwvideo').find('video').length)
$( "#my-video" ).find('.jwvideo').find('video').PlaybackRate=0.5;
});
1st alert coming as 1
2nd alert coming undefined
3rd alert is showing "source"
4th alert is 1
I am able to catch the div but not able to change the playback rate in jquery !!!
http://www.longtailvideo.com/support/forums/jw-player/feature-suggestions/32556/playbackrate-support/
following above link i also tried with java script and it worked using code below
(document.getElementsByTagName('video')[0].playbackRate=0.2.
but if i use above code how do i use this for multiple video since there is no ID involved in above code [no unique id is passed for above javascript]
Below is the div structure for the jwplayer
I found the answer for this, main issue which i faced for multiple video was how to make each video unique.i just had to get div by ID first and after get 'Video' tag than change playbackrate
adding the code below
var video = document.getElementById('exampleId')
var video_speed = video.getElementsByTagName('video')[0]
alert(video_speed.playbackRate)
video_speed.playbackRate=0.2;
alert(video_speed.playbackRate)
I even tried with multiple video, it worked fine
Found this script manually manipulating the DOM for custom speeds:
<script type="text/javascript">
jwplayer("video").setup({
image: 'https://<your_CDN_ID>.cloudfront.net/static/splash/<splash.png>',
width: 960,
height: 600,
flashplayer: "https://<your_CDN_ID>.cloudfront.net/assets/jwplayer.flash.swf",
html5player: "https://<your_CDN_ID>.cloudfront.net/assets/jwplayer.html5.js",
primary: 'html5',
sources: [
{ file: 'https://<your_CDN_ID>.cloudfront.net/static/videos/<video>.mp4' },
{ file: 'https://<your_CDN_ID>.cloudfront.net/static/videos/<video>.webm' }
]
});
var tag;
jwplayer().onReady(function(){
if (jwplayer().getRenderingMode() == "flash") {
return;
}
tag = document.querySelector('video');
tag.defaultPlaybackRate = 1.0;
tag.playbackRate = 1.0;
jwplayer().addButton("https://<your_CDN_ID>.cloudfront.net/assets/25.png", "", function(){
jwplayer().seek(jwplayer().getPosition());
tag.playbackRate = 0.25;
},"025");
jwplayer().addButton("https://<your_CDN_ID>.cloudfront.net/assets/05.png", "", function(){
jwplayer().seek(jwplayer().getPosition());
tag.playbackRate = 0.5;
},"05");
jwplayer().addButton("https://<your_CDN_ID>.cloudfront.net/assets/1.png", "", function() {
jwplayer().seek(jwplayer().getPosition());
tag.playbackRate = 1.0;
},"1");
jwplayer().addButton("https://<your_CDN_ID>.cloudfront.net/assets/125.png", "", function() {
jwplayer().seek(jwplayer().getPosition());
tag.playbackRate = 1.25;
},"125");
jwplayer().addButton("https://<your_CDN_ID>.cloudfront.net/assets/15.png", "", function() {
jwplayer().seek(jwplayer().getPosition());
tag.playbackRate = 1.5;
},"15");
jwplayer().addButton("https://<your_CDN_ID>.cloudfront.net/assets/2.png", "", function() {
jwplayer().seek(jwplayer().getPosition());
tag.playbackRate = 2.0;
},"2");
});
</script>
Instead of toggle like the excellent blogpost from Ethan there are speed buttons.
Just setting a custom speed:
document.querySelector('video').playbackRate=0.80;
https://developer.jwplayer.com/jw-player/demos/advanced/set-playback-rate/
only add line playbackRateControls in .setup()
jwplayer('user-player').setup({
playlist: 'https://cdn.jwplayer.com/v2/media/gaCRFWjn',
// Set the available playback rates of your choice
playbackRateControls: [0.75, 1, 1.25, 1.5]
});
Just add ids to your videos and use document.getElementsById (id) instead of document.getElementsByTagName.
document.getElementsById('yourid').playbackRate=0.2
I wrote a blog post about a how to do this in the JW Player, by the way. It might be helpful! - http://www.longtailvideo.com/blog/33860/slow-motion-with-jw-player

Capture group of HTML5 video screenshots

I am trying to generate a group of thumbnails in the browser out of a HTML5 video using canvas with this code:
var fps = video_model.getFps(); //frames per second, comes from another script
var start = shot.getStart(); //start time of capture, comes from another script
var end = shot.getEnd(); //end time of capture, comes from another script
for(var i = start; i <= end; i += 50){ //capture every 50 frames
video.get(0).currentTime = i / fps;
var capture = $(document.createElement("canvas"))
.attr({
id: video.get(0).currentTime + "sec",
width: video.get(0).videoWidth,
height: video.get(0).videoHeight
})
var ctx = capture.get(0).getContext("2d");
ctx.drawImage(video.get(0), 0, 0, video.get(0).videoWidth, video.get(0).videoHeight);
$("body").append(capture, " ");
}
The the amount of captures is correct, but the problem is that in Chrome all the canvases appear black and in Firefox they always show the same image.
Maybe the problem is that the loop is too fast to let the canvases be painted, but I read that .drawImage() is asynchronous, therefore, in theory, it should let the canvases be painted before jumping to the next line.
Any ideas on how to solve this issue?
Thanks.
After hours of fighting with this I finally came up with a solution based on the "seeked" event. For this to work, the video must be completely loaded:
The code goes like this:
var fps = video_model.getFps(); //screenshot data, comes from another script
var start = shot.getStart();
var end = shot.getEnd();
video.get(0).currentTime = start/fps; //make the video jump to the start
video.on("seeked", function(){ //when the time is seeked, capture screenshot
setTimeout( //the trick is in giving the canvas a little time to be created and painted, 500ms should be enough
function(){
if( video.get(0).currentTime <= end/fps ){
var capture = $(document.createElement("canvas")) //create canvas element on the fly
.attr({
id: video.get(0).currentTime + "sec",
width: video.get(0).videoWidth,
height: video.get(0).videoHeight
})
.appendTo("body");
var ctx = capture.get(0).getContext("2d"); //paint canvas
ctx.drawImage(video.get(0), 0, 0, video.get(0).videoWidth, video.get(0).videoHeight);
if(video.get(0).currentTime + 50/fps > end/fps){
video.off("seeked"); //if last screenshot was captured, unbind
}else{
video.get(0).currentTime += 50/fps; //capture every 50 frames
}
}
}
, 500); //timeout of 500ms
});
This has worked for me in Chrome and Firefox, I've read that the seeked event can be buggy in some version of particular browsers.
Hope this can be useful to anybody. If anyone comes up with a cleaner, better solution, it would be nice to see it.

progress bar for playing videos

I'm trying to add a progress bar that shows how far a videos into it's duration, but one that can be placed outside the video itself(like on another part of the screen). I've been looking around for some time, and have only found ones for showing the loading progress, which is what I don't need. Can anyone help me find where to find that, or supply one themselves even. just in case it's needed, here's the script for the video
var numb = $(this).index(),
videos = ['images/talking1.m4v', 'images/talking2.m4v', 'images/talking1.m4v', 'images/talking2.m4v', 'images/talking1.m4v', 'images/talking2.m4v'
],
myVideo = document.getElementById('myVid');
myVideo.src = videos[numb];
myVideo.load();
setTimeout(function(){
myVideo.play();
}, 200);
You could bind an event listener to the timeupdate event:
myVideo.addEventListener("timeupdate", function() {
// if the video is loaded and duration is known
if(!isNaN(this.duration)) {
var percent_complete = this.currentTime / this.duration;
// use percent_complete to draw a progress bar
}
});
Pick a max length for your progress bar, multiply it by percent_complete (which is between 0 and 1), and use that product as the current length of the bar.

Categories