I am new to Javascript... like super new :X and i am writing my very first script to try and automate video episodes of my favorite anime because the videos on the site don't have a autoplay feature after you click the link. I read about Video and Var = 'My video' to try and figure out how to tell the script, when page loads video .autoplay = true...but i just get to dead ends. here is where i am at:
var urlsToLoad = [
'http://Site1/Ep1',
'http://Site1/Ep2',
'http://Site1/Ep3',
'http://Site1/Ep4'
];
if (document.readyState == "complete") {
FireTimer ();
}
window.addEventListener ("hashchange", FireTimer, false);
function FireTimer () {
setTimeout (GotoNextURL, 5000); // 5000 == 5 seconds
}
function GotoNextURL () {
var numUrls = urlsToLoad.length;
var urlIdx = urlsToLoad.indexOf (location.href);
urlIdx++;
if (urlIdx >= numUrls) urlIdx = 0;
Once the first video link starts 'Site1/EP1', i have this going:
function myFunction() {
var vid = document.getElementById("925664"); <--Ctrl+F 'Videoid' from Source
vid.autoplay = true;
vid.load();
}
but it just stays died like 'click play to start' ..
I can really use help here PLZZZ and thank you.
Something like this:
<!-- HTML Page -->
<video id="925664"></video>
// Javascript
function myFunction() {
var vid = document.getElementById("925664"); // <--Ctrl+F 'Videoid' from Source
vid.src = "path/to/file.mp4";
//vid.autoplay = true; // not really anything that's useful
vid.load();
vid.play();
}
Warning: Most mobile devices don't allow media files to play via code and require human interaction (click/touch) in order to start playback. However, on desktops this isn't a problem.
Try using the play() method instead.
function myFunction() {
var vid = document.getElementById("925664");
vid.play();
}
Related
I want to run a function after checking if an audio file is downloaded.
My js:
// https://freesound.org/people/jefftbyrd/sounds/486445/
var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.mp3";
var audioElem = document.querySelector("audio");
var startElem = document.querySelector("button");
var resultScreen = document.querySelector("p");
function checkAudio() {
audioElem.setAttribute("src", audioFile);
if (audioElem.complete) {
resultScreen.innerHTML = "loaded audio";
}
}
startElem.addEventListener("click", function(){
checkAudio();
});
Codepen: https://codepen.io/carpenumidium/pen/KKPjRLR?editors=0011
I want the "loaded audio" text to be displayed, after the audio file has completed downloading. The code to check if the file has completed downloading might be utter bs so please go easy on me.
Thanks for your help!
You are not using the correct even to check the loaded status. See below a snippet that will do that.
You need to use the canplaythrough event that means
The browser estimates it can play the media up to its end without
stopping for content buffering.
The event you are using complete is actually triggered when
The rendering of an OfflineAudioContext is terminated.
// https://freesound.org/people/jefftbyrd/sounds/486445/
var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.mp3";
var audioElem = document.querySelector("audio");
var startElem = document.querySelector("button");
var resultScreen = document.querySelector("p");
function checkAudio() {
audioElem.setAttribute("src", audioFile);
audioElem.addEventListener('canplaythrough', (event) => {
resultScreen.innerHTML = "loaded audio";
});
}
startElem.addEventListener("click", function() {
checkAudio();
});
<audio controls="controls" src=""></audio>
<button>load audio</button>
<div class="result">
<h1>Audio file status:</h1>
<p></p>
</div>
For more on audio elements refer MDN Docs
Hope this helps :)
You can use the onload event to get notified when the full audio is loaded:
function checkAudio() {
audioElem.setAttribute("src", audioFile);
audioElem.onload= ()=>{
resultScreen.innerHTML = "loaded audio";
}
}
startElem.addEventListener("click", function(){
checkAudio();
});
I'm trying to control a youtube iframe in my squarespace website. I want it to autoplay when the page loads and then if I scroll and it's not in the viewport anymore, I want it to pause.
Here is what I did:
This is my iframe:
<iframe id="ytplayer" width="560" height="315" src="https://www.youtube.com/embed/uuRC8Pmud3o?enablejsapi=1&rel=0&showinfo=0&controls=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
And this is my script:
<script>
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function YouTube player
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// The API calls this function when the player's state changes.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
done = true;
}
// Loop the video
if (event.data == YT.PlayerState.ENDED) {
player.playVideo();
}
}
// On scroll Pause/Play the video player
$(window).scroll(function() {
var top_of_element = $("#ytplayer").offset().top;
var bottom_of_element = $("#ytplayer").offset().top + $("#ytplayer").outerHeight();
var bottom_of_screen = $(window).scrollTop() + $(window).height();
var top_of_screen = $(window).scrollTop();
if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
// The element is visible, trigger play click event
player.playVideo()
}
else {
// The element is not visible, trigger pause click event
player.pauseVideo()
}
});
</script>
I tried adding the script to squarespace using many ways but it's not working. Where has the script to be injected?
What's wrong with my code?
According to Youtube IFRAME API, just add autoplay=1 at the end of your URL like:
<iframe id="ytplayer" type="text/html" width="640" height="360"
src="https://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&origin=http://example.com"
frameborder="0"></iframe>
I think this is also confirmed in the squarespace forum.
I have just figured this out.
Squarespace creates it's own players and also it dynamically creates iframes so it's a bit complicated. Also getting player using DOM element doesn't seems to work and all iframe elements have the same id = "player" so that adds up to the problem.
The code below is what I have come to literally 5min ago.
Just copy/paste to the header code injection in the Squarespace config.
What it does is it acquire all the original YouTube API players as soon as possible and pause playback to avoid horrible lag when my old GPU tries to video-decode all those video instances. Then I have a code which plays the video when it appears on the screen and pauses videos that are not visible anymore. Now it plays smoothly and I can add even more videos. In my case you can see one full-screen video at a time as you scroll down. I have 7x 720p videos stacked up. It looks cool, but I found out that my GPU is lagging badly when more than 5 videos were used, initially I was thinking that it's a network speed problem but my task manager showed 100% on GPU video-encoding. So far worked on Firefox and Chrome.
I have just managed to make this work so there is a lot of testing and tweaking to be done.
USE ON YOUR OWN RISK ! :)
<script type="text/javascript">
// Prepare YouTube iframe API ..
// this is probably redundant, but works fine
var tag = document.createElement ('script');
tag.id = 'iframe-api';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName ('script')[0];
firstScriptTag.parentNode.insertBefore (tag, firstScriptTag);
// When Iframe is ready ..
var iframes = [];
var players = [];
function onYouTubeIframeAPIReady () {
// console.log ("onYouTubeIframeAPIReady");
var player_containers = document.querySelectorAll (".sqs-video-background.content-fill");
for (var i = 0; i < player_containers.length; i ++) {
player_containers [i].addEventListener ("DOMNodeInserted", function (e) {
var node = e.target;
if (node.tagName.toUpperCase () === "IFRAME") {
// console.log ("PLAYER : " + node.id + " TAG : " + node.tagName);
iframes.push (node);
// unfortunately it seems that we cannot catch the player creation event so
// the actual players are probably created after this code
// by calling this function we can catch previous players early on
// except the last one
initPlayers ();
}
}, false);
}
}
function initPlayers () {
// they have all the same id (!!!)
// however it seems it picks the last created one so not the same one over and over
// I didn't touched this, it works so far
var player = YT.get ("player");
if (player !== undefined) {
players.push (player);
pausePlayer (player);
}
}
function playPlayer (player) {
// this happends when player is not fully initialized yet
if (typeof player.pauseVideo === "function") {
player.playVideo ();
} else {
// if the player is not ready yet catch the event
player.addEventListener ('onReady', function (event) {
player.playVideo ();
});
}
}
function pausePlayer (player) {
// this happends when player is not fully initialized yet
if (typeof player.pauseVideo === "function") {
player.pauseVideo ();
} else {
// if the player is not ready yet catch the event
player.addEventListener ('onReady', function (event) {
player.pauseVideo ();
});
}
}
function isInViewport (element, edge) {
var h = window.innerHeight; // viewport height
var r = element.getBoundingClientRect (); // elements bounding rect in viewport coordinates
// console.log ("top : " + r.top);
// console.log ("bottom : " + r.bottom);
// console.log ("height : " + h);
// add extra margin to the viewport to ensure that
// big enough portion of the object is already visible
var e = h * Math.min (edge, 0.4); // relative viewport factor, max 40%
var top = r.top - e;
var bottom = r.bottom - e;
h = h - e*2;
return (!((top > h) || (bottom < 0)));
}
window.onload = function(e){
// console.log ("loaded");
initPlayers (); // to catch the last one !
// console.log ("players : " + players.length);
function onScroll () {
for (var i = 0; i < players.length; i ++) {
var player = players [i];
var iframe = player.getIframe ();
var container = iframe.parentNode;
if (isInViewport (container, 0.0)) {
playPlayer (player); } else {
pausePlayer (player);
}
}
}
// in the case object is already in the viewport
onScroll ();
window.addEventListener ("resize", onScroll);
window.addEventListener ("scroll", onScroll);
}
</script>
I'm create audio button. The sound will start when we click on the button and we will click again stop it. I want random uninterrupted sound when we press the button. I created a sample JS, but when the sound ends, the sound does not change automatically.
I recently tried the code below. When I use this code, the button is starting to sound(okey), the sound is changing(okey), but when we pause click, the sound is not stopping. The sound changes, the sound changes again when we click again. What kind of method should I try?
var sounds = new Array();
sounds[0]="http://static1.grsites.com/archive/sounds/background/background001.mp3";
sounds[1]="http://static1.grsites.com/archive/sounds/background/background002.mp3";
sounds[2]="http://static1.grsites.com/archive/sounds/background/background003.mp3";
sounds[3]="http://static1.grsites.com/archive/sounds/background/background004.mp3";
sounds[4]="http://static1.grsites.com/archive/sounds/background/background005.mp3";
document.getElementById("playpause").addEventListener("click", function getRandomSounds(){
var audio = document.getElementById('testAudio');
var randomNum = Math.floor(Math.random() * sounds.length);
document.getElementById("testAudio").src = sounds[randomNum];
if(this.className == 'is-playing'){
this.className = "";
this.innerHTML = "Pause"
audio.pause();
}else{
this.className = "is-playing";
this.innerHTML = "Play";
audio.play();
}
document.getElementById("testAudio").addEventListener("ended", getRandomSounds);
getRandomSounds();
});
<html>
<body>
<input type="checkbox" value="None" id="playpause" name="check" />
<label for="playpause" tabindex=1></label>
<audio id="testAudio"></audio>
</body>
</html>
try removing the following this code:
document.getElementById("testAudio").addEventListener("ended",
getRandomSounds);
It looks like there were a few logical problems with the solution you had. The biggest ones were confusion with referencing elements for checkbox vs. label (so I simplified to a button), and that you were using the same event for play/pause as you were for queing the next item. So, as soon as it would try to queue one, it would also pause.
<html>
<body>
<input type="button" value="Play" id="playpause">
<audio id="testAudio"></audio>
</body>
</html>
var sounds = new Array();
sounds[0] = "http://static1.grsites.com/archive/sounds/background/background001.mp3";
sounds[1] = "http://static1.grsites.com/archive/sounds/background/background002.mp3";
sounds[2] = "http://static1.grsites.com/archive/sounds/background/background003.mp3";
sounds[3] = "http://static1.grsites.com/archive/sounds/background/background004.mp3";
sounds[4] = "http://static1.grsites.com/archive/sounds/background/background005.mp3";
document.getElementById("playpause").addEventListener("click", function() {
var audio = document.getElementById('testAudio');
var doPlay = this.className != 'is-playing' && audio.src != null;
if (audio.src == null) {
getRandomSound();
}
if (this.className == 'is-playing') {
this.className = "";
this.value = "Play"
audio.pause();
} else if(doPlay) {
this.className = "is-playing";
this.value = "Pause"
audio.play();
}
document.getElementById("testAudio").addEventListener("ended", getRandomSounds);
});
function getRandomSound() {
var audio = document.getElementById('testAudio');
var randomNum = Math.floor(Math.random() * sounds.length);
document.getElementById("testAudio").src = sounds[randomNum];
audio.play();
};
I also updated it here so that the pause is just a pause and won't change the selected track until the one you're on has ended. I'm not sure if that's the intended or not, but by the description, I'm guessing that's what you'd want. Otherwise, it's a simple edit to go to a new track on every new start.
I've done a reasonable amount with playing sound from the browser, and the best option I found was to use a soundmanager js. I used SoundManager2 from here: http://www.schillmania.com/projects/soundmanager2/demo/template/ I'm sure there are others that would work though. The problem is that different browsers have different capabilities and expectations, so in order to get a best-case working scenario, you need something that uses html5 with flash as a backup option. I can verify that the one I linked works in Edge, Firefox, and Chrome (desktop and mobile), but I can't verify any other browsers for certain. I've been using it for audio responses in a warehouse application, so I can also verify that it's reliable when implemented correctly, but I haven't used play/pause on it or the interface. I just play from the background.
here's my setup as an implementation example if you end up working with that one:
var soundReady = false;
var QueuedSounds = [];
soundManager.setup({
url: '/Scripts/SoundManager/',
// flashVersion: 9, // optional: shiny features (default = 8)
preferFlash: false,
onready: function () {
// Ready to use; soundManager.createSound() etc. can now be called.
soundReady = true;
QueuedSounds.Each(function (s) {
var mysound = soundManager.createSound({
id: 'mySound',
url: s.filename,
autoLoad: true,
autoPlay: true,
onfinish: function () {
this.destruct();
},
volume: 100
});
});
}
});
function PlaySound(filename, mime) {
if (soundObject != null) {
$(soundObject).remove();
soundObject.removed = true;
soundObject = null;
}
if (soundReady) {
var mysound = soundManager.createSound({
id: 'mySound',
url: filename,
autoLoad: true,
autoPlay: true,
onfinish: function () {
this.destruct();
},
volume: 100
});
}
else {
QueuedSounds.push({ filename: filename, mime: mime });
}
}
I have created a fiddle of my function here( http://jsfiddle.net/rhy5K/10/ ) . Now i want to provide the Sound "Mute/unpute" option for users. Example if i click on "a link then sound playing like Get ready,5,4,3,2,1 should be mute and vice-versa.
I am thinking like to call a to toggle_sound function on click, but i am confuse like what should i write inside the function to mute the sound.
Please provide me a logic, or a solution for my problem.
Explanation using code example:
I want to MUTE/UnMUTE this below sound playing
var playGetReady = function (done) {
var ids = ['audiosource', 'a_5', 'a_4', 'a_3', 'a_2', 'a_1'],
playNext = function () {
var id = ids.shift();
document.getElementById(id).play();
if (ids.length) {
setTimeout(playNext, 1000);
} else {
done();
}
};
playNext();
};
Warning: This JS fiddle demo may play sound on load
Try
HTML5 Video_tag for display video with audio
or
this below example along with html5 with jquery
window.my_mute = false;
$('#my_mute_button').bind('click', function(){
$('audio,video').each(function(){
if (!my_mute ) {
if( !$(this).paused ) {
$(this).data('muted',true); //Store elements muted by the button.
$(this).pause(); // or .muted=true to keep playing muted
}
} else {
if( $(this).data('muted') ) {
$(this).data('muted',false);
$(this).play(); // or .muted=false
}
}
});
my_mute = !my_mute;
});
I think you can use:
document.getElementById(id).volume = 1;
or
document.getElementById(id).volume = 0;
I am currently modifying a web app for iPad. I am trying to attach an audio soundtrack to the image slideshow. I currently have the audio files playing when the user hits the slideshow navigation controls but I can't seem to figure out how to make the audio play when the slides have automatically started.
When the nextBg() function in my main.js file moves from the current background image to the next I want it to play the next audio file in the list. The play function is: playAudio(). How do I do this?
The codes and files I am currently working with are:
function nextBg() {
if(bgRunning) return false;
clearInterval(bgTimer);
if(!$('#bgImages li.active').is(':last-child'))
$('#bgImages li.active').removeClass('active').next().addClass('active');
else
$('#bgImages li.active').removeClass('active').parent().find('li:first-child').addClass('active');
runBg();
}
function playAudio(path){
if(audioSupport){
var isPlaying = !myAudio.paused;
var canPlayMp3 = !!myAudio.canPlayType && "" != myAudio.canPlayType('audio/mpeg');
var canPlayOgg = !!myAudio.canPlayType && "" != myAudio.canPlayType('audio/ogg; codecs="vorbis"');
if(canPlayMp3)
myAudio.src = path+'.mp3';
else if(canPlayOgg)
myAudio.src = path+'.ogg';
myAudio.removeEventListener('ended', arguments.callee, false);
myAudio.addEventListener('ended', audioAddEndedListener , false);
if(autoPlay || isPlaying)
{
myAudio.play();
$('#audioControls .pause').css('display','block');
$('#audioControls .play').css('display','none');
}else{
$('#audioControls .play').css('display','block');
$('#audioControls .pause').css('display','none');
}
}
}
function audioAddEndedListener()
{
if(loop){
this.currentTime = 0;
this.play();
}else{
this.removeEventListener('ended', arguments.callee, false);
setNextAudio();
path = $('#audioList li.active').html();
playAudio(path);
myAudio.addEventListener('ended', audioAddEndedListener, false);
}
}
http://platinum.megatron.co.nz/main.js
http://platinum.megatron.co.nz/kitchen/video.html
Just call your playAudio() method inside the playBg() method after you swap the image.