play Audio tag onload in a specific time(ogg/mp3) using javascript - javascript

Load Audio tag in a specific time(mp3) using javascript.
Current code bellow, complety ignores currentTime.
My objective is to autoplay a mp3 file based on time(seconds) of the computer hardware clock.
<!DOCTYPE html>
<html>
<body>
<button onclick="setCurTime()" type="button">Set time position to 5 seconds</button>
<br>
<audio id="audio1" controls="controls">
<source src="http://attackbeat.com/audio/Masayume%20Chasing.mp3" type="audio/mp3">
Your browser does not support HTML5 video.
</audio>
<script>
var time = new Date();
var timex = time.getSeconds();
myAudio=document.getElementById("audio1");
window.onload = function () {
myAudio.play();
myAudio.currentTime=10;
}
function setCurTime()
{
myAudio.currentTime=timex;
myAudio.play();
}
</script>
</body>
</html>

You can seek to the given time only once the meta data is available:
var audio = document.getElementById('audio1');
audio.onloadedmetadata = function() {
audio.currentTime = new Date().getSeconds(); // autoplay based on current time (seconds)
audio.play();
};

Related

How to select the time of a video in html?

I am creating a website with vue.js where a user can select the time when something pops up in a video. The problem is that I cannot select the time of the video.
For example:
The user wants an image to popup at 5:00 in his video. How can I let the user select the time and let the image display at the right time?
Here is how to do it with raw javascript. Just adopt it to your code.
<!DOCTYPE html>
<html>
<body>
<video width="200" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
<br>
<big><span id="popup">Here will be popup</span></big>
<br>
<label for="time_to_popup">do popup after (secs): </label>
<input type="text" id="time_to_popup" value="2" name="time_to_popup">
<p>
Video courtesy of
Big Buck Bunny.
</p>
<script>
var intervalID = null;
// get video object
const video = document.querySelector('video');
// if play is started set interval to check play time
// and do popup if playing time bigger than popup trigger time
video.addEventListener('play', (event) => {
intervalID = setInterval(function() {
if (video.currentTime > parseInt(document.getElementById("time_to_popup").value)) {
document.getElementById("popup").textContent = "BOOOOOOM !!!!!";
}
}, 1000);
});
// remove interval and revert popup message to normal text
// if video is paused
video.addEventListener('pause', (event) => {
document.getElementById("popup").textContent = "Here will be popup";
clearInterval(intervalID);
});
</script>
</body>
</html>
In short:
html5 video object has currentTime (video.currentTime) attribute that can be used to get current time. Also you can use paused (video.paused) attribute to check is video playing.

Randomize Background Video with Sound, after clicking function

I wrote this code a while back, and it allowed users to click and refresh the page to autoplay a RANDOM background video with sound.
This is the function that they click that loads the function
https://pastebin.com/0XXEHvQQ
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> press me PLAY VIDS :)</a></font></p>
</div>
https://pastebin.com/PD5qdNDM
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> -> press me to fix the site :) <-</a></font></p>
</div>
</div>
</div>
</div>
<!-- Scripts -->
<script src="js/parallax.js"></script>
<script>
// Pretty simple huh?
var scene = document.getElementById('scene');
var parallax = new Parallax(scene);
</script>
</script>
<script src="js/custom.js"></script>
<script>
let volumeInterval;
function loaded(){
setInterval(loop, 600);
volumeInterval = setInterval(volume, 1);
}
function unload(){
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
console.log("unloaded");
}
function volume() {
try {
document.getElementsByTagName("video")[0].volume = 0.15;
console.log("done!");
clearInterval(volumeInterval);
}
catch (e) {
console.log("waiting..");
}
}
function ok() {
document.write(unescape(
and heres the unescaped code
https://pastebin.com/YJwbG2mC
<!-- VIDEO GRABBB -->
<video preload="auto" autoplay="true" loop="true">
<source id="player" src="5.mp4">
<script>
var video = document.currentScript.parentElement;
video.volume = 0.33;
//document.getElementById('player').currentTime = 20;
</script>
<script>
var video = document.getElementById("player");
video.addEventListener("timeupdate", function(){
if(this.currentTime >= 1000) {
location.reload();
}
});
</script>
<script type="text/javascript">
var video = document.getElementsByTagName('video')[0];
video.onended = function() {
location.reload();
};
</script>
<script>
document.getElementById("player").src = "/" + Math.floor((Math.random()*7)+1) + ".mp4";
</script>
</video>
No matter how I try to adjust the unescaped code, I can't get the MP4 to autoplay after clicking the function.
Here is my live site that I no longer can access: form.wtf
According to the HTML Spec on the Source Element,
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.
Therefore, no matter what you do to the source element, you can't change the video unless the new src is applied directly to the video element.
Replacing the source element also has no effect on the video that plays. The source element's src attribute may changed but the video will keep on playing.
Therefore, you should leave your source's src attribute empty until the JavaScript code sets it or
Leave out the source tag all together and apply the src straight to the video.
Math.floor(Math.random() * 7 + 1); is exactly the same thing as Math.ceil(Math.random() * 7);
document.querySelector('#player > source').src = `/${Math.ceil(Math.random() * 7)}.mp4`;
<video id="player" preload="auto" autoplay loop>
<source src="">
</video>

HTML5 video with audio separate cannot control volume

I use video tag of html5 by separate audio from video like this code.
<video id="myvideo" controls >
<source src="output.webm" type="video/webm">
<audio id="myaudio" controls="">
<source src="audio1.ogg" type="audio/ogg"/>
</audio>
</video>
<script>
var myvideo = document.getElementById("myvideo");
var myaudio = document.getElementById("myaudio");
var change_time_state = true;
myvideo.onplay = function(){
myaudio.play();
if(change_time_state){
myaudio.currentTime = myvideo.currentTime;
change_time_state = false;
}
}
myvideo.onpause = function(){
myaudio.pause();
change_time_state = true;
}
</script>
It can play video and audio but it cannot change audio volume. Can I fix it to change volume ?
Use the MP4 video and check your source URL.
You might be searching the DOM volume Property, check it in w3school
In your case the solution is:
myaudio.volume = anynumber;
Must be a number between 0.0 and 1.0.
Example values:
1.0 is highest volume (100%. This is default)
0.5 is half volume (50%)
0.0 is silent (same as mute)

How do I make a random video play on pageload?

I'm trying to make a random video player in html/js.
It is supposed to play a different video on pageload and as soon as one video is over, it should play another one.
HTML
<video width="320" height="240" autoplay>
<source src="abcdefg.com/example1.mp4" type="video/mp4">
<source src="abcdefg.com/example2.mp4" type="video/mp4">
</video>
JS
<script>
var videos = [
[{type:'mp4', 'src':'abcdefg.com/example1.mp4'}],
[{type:'mp4', 'src':'abcdefg.com/example2.mp4'}],
];
$(function() {
var number = Math.floor(Math.random()*videos.length);
$(this).find('source').each(function(index){
videoSrc = videos[number][index].src;
$(this).attr('src', videoSrc);
$('video').load();
$('video').play();
});
});
</script>
However, my current code plays the same video every page reload and as soon as it's over, nothing happens.
How do I need to optimize my code so it automatically plays a different video on every pageload + when the previous video is over?
Try this,I have added an event listener to video end property and called the newvideo() function ,so that every time the video finishes a new random video is loaded from array.I could'nt find more video urls ,you can test and let me know if it works for you.
$(document).ready(function(){
var videos = [
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}]
];
// selecting random item from array,you can make your own
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src)
{
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
//vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(e)
{
newvideo(randomitem[0].src)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video width="320" height="240" autoplay id="myVideo">
</video>

How to pause/stop playing audio and replace with new audio file

So when the user clicks a button an audio file plays from an array of audio files(around 2 sec clip), which works fine. However, if the user repeatedly clicks the button, the audio files start to play over each other. Ideally, I would like to stop/pause the previous audio file and then play the new audio file. This is what I've tried to avail:
$scope.sounder=function(){
$scope.rs=$scope.diff[$scope.workout_index].audiorep;
$scope.ms=$scope.diff[$scope.workout_index].audiomove;
//var movesound = new Audio ($scope.ms);
//ar repsound = new Audio ($scope.rs);
var movesound = new Media($rootScope.getMediaURL($scope.ms));
var repsound = new Media($rootScope.getMediaURL($scope.rs));
if($scope.muter==0){
movesound.pause();//DOES NOT WORK
movesound.stop();//STOPS ALL AUDIO FROM PLAYING, SO NOTHING PLAYS
$timeout(function() {
movesound.play();
}, 1000);
$timeout(function() {
repsound.play();
}, 3000);
}
if($scope.muter==1){
console.log("Rachel has been muted");
return;
}
}
You can achieve the functionalities with JavaScript in Cordova unless you specifically need AngularJS in your app.
<audio controls id="myAudio">
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the HTML5 audio tag.
</audio>
Now using script to add functionalities -
<script>
var aud= document.getElementById("myAudio");
function playAud() {
aud.play();
}
function pauseAud() {
aud.pause();
}
function myFunction() {
isSupp = aud.canPlayType("audio/mp3");
if (isSupp == "") {
aud.src = "audio.ogg";
} else {
aud.src = "audio.mp3";
}
aud.load();
}
</script>
See other answers of this question on for changing source of audio with JavaScript.
Refer w3schools HTML Audio Video DOM reference Page for further attributes and functions.

Categories

Resources