I am working on an IDE based off of JavaScript. I need to figure out how to play videos using only JavaScript. I have looked online and found next to nothing.
Here's the code I have right now:
var vid = document.createElement('video');
vid.src = src;
vid.autoPlay = true;
document.body.appendChild(vid);
vid.play(); To play a video.
Link to tutorial: W3 schools
var vid = document.getElementById("myVideo");
function playVid() {
vid.play();
}
function pauseVid() {
vid.pause();
}
DEMO
EDIT: Here is how you add controls
HTML:
<button id="playPause">Pause</button>
JS:
var pp = document.getElementById('playPause');
pp.onclick = function(){
if(vid.paused){
vid.play();
pp.innerHTML = "Pause";
}else{
vid.pause();
pp.innerHTML = "Play";
}
};
DEMO2
Adding default controls
vid.controls = true;
Related
I want to build a video playlist using html css javascript.
I looked through google and youtube and found relevant tutorials
But all of those controls the video using the mouse
Can anyone please direct me to a source that helps me learn video controls using the only keyboard
Thanks in advance
var myVideo = document.getElementById("videoplayer");
function playPause() {
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
function makeBig() {
myVideo.width = 560;
}
function makeSmall() {
myVideo.width = 320;
}
function makeNormal() {
myVideo.width = 420;
}
function playSound(buffer) {
aSoundSource = audioContext.createBufferSource(); source.
aSoundSource.buffer = buffer;
aSoundSource.connect(gainNode);
gainNode.connect(analyser);
var volX = volControl();
//gainNode.gain.value = 0.1;
gainNode.gain.value = volX;
analyser.connect(audioContext.destination);
aSoundSource.start(0);
document.title = document.getElementById("files").value;
playing = true;
requestAnimFrame(drawVisualisation);
}
///////////////////////////////////////
function play(){
var audio = new Audio('test.mp3');
audio.play();
}
second function is working perfectly its i have called particular audio to play its working for button here i want to input a song and play
Havent tested but this is the rough idea
document.getElementById("inputFile").onchange = loadMusic
function loadMusic(e) {
console.log(e.target.value)
var audio = new Audio(e.target.value)
audio.play();
}
<input type="file" id="inputFile">
So, I'm a complete amateur when it comes to coding, but I still like to fiddle around with it.
I'm currently working on a html/jS/PHP based soundboard and I can't figure out how to stop sound from playing when pressing a button to play another one.
<script type="text/javascript" charset="utf-8">
$(function() {
$("audio").removeAttr("controls").each(function(i, audioElement) {
var audio = $(this);
var that = this; //closure to keep reference to current audio tag
$("#doc").append($('<button>'+audio.attr("title")+'</button>').click(function() {
that.play();
}));
});
});
</script>
I hope someone understands that. Thanks in advance.
There is also a PHP code to fetch the audio file automatically from the folder to the front end, probably unnecessary info for this problem.
This is not very difficult to do if you use HTML5 which introduced the HTMLAudioElement.
Here is the minimal code for what you are trying to do:
// Let's create a soundboard module ("sb")
var sb = {
song: null,
init: function () {
sb.song = new Audio();
sb.listeners();
},
listeners: function () {
$("button").click(sb.play);
},
play: function (e) {
sb.song.src = e.target.value;
sb.song.play();
}
};
$(document).ready(sb.init);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Audio</title>
</head>
<body>
<button value="https://www.gnu.org/music/FreeSWSong.ogg">Song #1</button>
<button value="https://www.gnu.org/music/free-software-song-herzog.ogg">Song #2</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
You may also consider libraries like howler.js to help you in the development process.
What you could do, is before start playing a new audio pause all available audio on the page. Something like this.
var audioOne = document.querySelector('#audio-1');
var audioTwo = document.querySelector('#audio-2');
var allAudios = document.querySelectorAll('audio');
function stopAllAudio(){
allAudios.forEach(function(audio){
audio.pause();
});
}
document.querySelector('#play-1').addEventListener('click', function(){
stopAllAudio();
audioOne.play();
})
document.querySelector('#play-2').addEventListener('click', function(){
stopAllAudio();
audioTwo.play();
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<audio id="audio-1"
src="http://developer.mozilla.org/#api/deki/files/2926/=AudioTest_(1).ogg">
</audio>
<audio id="audio-2"
src="http://www.w3schools.com/html/horse.mp3">
</audio>
<button id="play-1">
play audio 1
</button>
<button id="play-2">
play audio 2
</button>
</body>
</html>
Instead of adding audio using <audio> tag you could use HTMLAudioElement.
You can stop and reset an audio element by pausing it and setting its current time to 0. You would need to do this whenever a button is clicked. Example:
// Available sounds:
const sounds = {
"Bottle": "http://freewavesamples.com/files/Bottle.wav",
"Bamboo": "http://freewavesamples.com/files/Bamboo.wav"
}
// Load audio elements:
let audios = {};
for (let [title, url] of Object.entries(sounds)) {
audios[title] = new Audio(url);
}
// Create board buttons:
let board = document.getElementById("board");
for (let title of Object.keys(audios)) {
let button = document.createElement("button");
button.textContent = title;
button.dataset["audio"] = title;
board.appendChild(button);
}
// Handle board button clicks:
board.addEventListener("click", function(event) {
let audio = audios[event.target.dataset["audio"]];
if (audio) {
// Pause and reset all audio elements:
for (let audio of Object.values(audios)) {
audio.pause();
audio.currentTime = 0;
}
// Play this audio element:
audio.play();
}
});
<div id="board"></div>
In case you want to leverage the full power of the Web Audio API, you would probably start building your soundboard similar to this:
// Load buffer from 'url' calling 'cb' on complete:
function loadBuffer(url, cb) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.responseType = 'arraybuffer';
request.onload = () => context.decodeAudioData(request.response, cb);
request.send();
}
// Available sounds:
const sounds = {
"Bottle": "url/to/bottle.wav",
"Bamboo": "url/to/bamboo.wav"
};
let audioCtx = new (AudioContext || webkitAudioContext)(),
board = document.getElementById("soundboard"),
buffers = {},
source;
// Load buffers:
for (let [title, url] of Object.entries(sounds)) {
loadBuffer(url, buffer => buffers[title] = buffer);
}
// Create board buttons:
for (let title of Object.keys(sounds)) {
let button = document.createElement("button");
button.textContent = title;
button.dataset["buffer"] = title;
board.appendChild(button);
}
// Handle board button clicks:
board.addEventListener("click", function(event) {
let buffer = buffers[event.target.dataset["buffer"]];
if (buffer) {
if (source) source.stop();
source = audioCtx.createBufferSource();
source.buffer = buffer;
source.connect(audioCtx.destination);
source.start();
}
});
<div id="soundboard"></div>
Please note that the sound URLs given above must either be on the same domain or available under the same origin policy (see CORS headers).
Below code may help others:
var audioMap = new Map();
var rappers = document.querySelectorAll('.rapper');
rappers.forEach(function(rapper){
audioMap.set(rapper, new Audio());
rapper.addEventListener('click', function(){
var audio = new Audio($(this).data('audio'));
audio.play();
audioMap.set(this, audio);
var current = audioMap.get(this);
// console.log('get', current);
audioMap.forEach(function(audio){
if( audio != current ){
audio.pause();
audio.currentTime = 0;
}
});
});
});
For the ones that don't use the audioTag in HTML5 and want to use only vanilla js this may help ya
var songplaying = null; //This is where we will store the current playing song
function playsong(song_name){
//settings
var playing = null;
if(songplaying==null){ //If a song isn't stored that means that it's not playing and vice versa
playing = false;
}else{
playing = true;
}
var dir = "./songs/"+song_name+".mp3"; //Here we get the directory of the song
var song = new Audio(dir); //Making a new audio element
if(!playing){ //This runs when no song is playing
song.play();
songplaying=song; //We save the current playing song
}else{ //This runs when another song is already playing
var song_alredyplaying = songplaying; //We get the audio element (song)
song_alredyplaying.pause(); //Pause the song
song.play(); //Then we play the new song
songplaying=song; //Save the current playing song
}
}
//Example
var playbtn = document.querySelector(".play");
playbtn.addEventListener('click', function(){
playsong("the song name");
};
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();
}
I saw this deface from anonymous, so I want to add a hidden chiptune song when playing the game, but got kinda lost.
<script type="text/javascript" src="http://www.ussc.gov/include/js/konami.js"></script>
<script type="text/javascript">
var success = function() {
document.body.style.backgroundImage = "url(http://3.bp.blogspot.com/-vKs53Qq5mBI/T9vCsCb-irI/AAAAAAAAB8U/CZsS0iY5RjY/s1600/14685_1_other_wallpapers_anonymous.jpg)";
document.body.style.backgroundSize = "100%";
if(window.KICKASSGAME){window.KICKASSGAME.menuManager.menu.messageTypeChangeShip('242,0');
window.KICKASSGAME.menuManager.destroy()}else{
alert("AntiSec CAEK-mode activated... Destroy the system! Controls: up, down, left, right, space to fire.");
var KICKASSVERSION='2.0';
var s = document.createElement('script');
s.type='text/javascript';document.body.appendChild(s);
s.src='//hi.kickassapp.com/kickass.js';
void(0);}
}
var konami = new Konami(success);
</script>
play is the method you are looking for
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'YourSong.ogg');
audioElement.load()
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
Check this out.. It may help you..!
function play_sound(url){
if(play_html5_audio){
var snd = new Audio(url);
//code
snd.play();
}else{
var sound = $("<embed id='sound' type='audio/mpeg' />");
//code
$('body').append(sound);
}
}
play_sound('beep.mp3');
Source Code found # Automatically playing audio with HTML5 and Javascript