New to Javascript, need help with HTML5 audio "playlist" - javascript

im trying to create a sort of playlist feature that will work on the iPhone using a combination of HTML5 and javascript. I'm very new to the platform and I was hoping maybe someone here could help me identify the problem with my code. The first song properly autoplays, but when it ends the next one does not load and play. The javascript code for my site is provided below, thanks in advance. (my apologies if this code is terribly messed up, i assembled this from what iv learned and what i could find different places online)
<script type="text/javascript">
var songname="Bottoms Up";
var counter=1;
var totalsongs=3;
while (counter<=totalsongs-1) {
document.write(<h2>songname</h2>);
switch (counter) {
case 1:
var nextSong="audio/Hey.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="Hey";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
case 2:
var nextSong="audio/I Like It.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="I Like It";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
} //switch close
} //while close
</script>
<center><audio src="audio/Bottoms Up.mp3" autoplay controls /></center>

A few things:
Give the audio element an id:
<audio src="audio/Bottoms Up.mp3" autoplay controls id="audioPlayer" /></center>
Use arrays instead of many variables:
var songs=({{"title": "First title","filename":"firstfile.mp3"},
{"title": "Second title","filename":"secondfile.mp3"}});
Listen for the event ended like this:
document.getElementById("audioPlayer").addEventListener("ended", nextSong, false);
And put the script in the <head> element.

var audioPlayer=document.getElementById('audioPlayer');
… will error, since the element doesn't have an id.

Related

How do I add a custom text button to the control bar of the VideoJS Player v.7?

I have tried various snippets of code that I've found online, but I can't get any of them to work with the current version of VideoJS, which is version 7. I'm very new to javascript programming, and the documentation does not give example code on how to implement this. There is a codepen here that can be used to experiment with customizing the player: https://codepen.io/heff/pen/EarCt This is the link to the VideoJS player documentation on adding a button to the player: https://docs.videojs.com/button
I've tried inserting code from various web page and 5-6 different discussions I found on StackExchange, but none of them make a button appear next to the video progress bar.
I'm simply trying to create a button with the text "Exit Course" that will appear to the right of the video progress bar, and that will execute a javascript function when pressed.
Could someone familiar with VideoJS please take a look at the codepen link above to see if they can add such a button to the player? Thank you!
I'm required to add some code to this question, so here is one piece of code that I tried on codepen:
var setup = {
'techOrder' : ['html5', 'flash'],
'controls' : true,
'preload' : 'auto',
'children':{
'controlBar': {
'children': {
'playbackSpeedPopoverMenu': {},
'selectBitrateControlButton': {src:videosrc},
'verticalVolumeMenuButton': {},
'volumeControl': false,
'muteToggle':false,
'liveDisplay':false,
}
}
};
var player = new vjs.Player(vjs.el("id_of_my_video_element_note_that_theres_no_poundsign"),
setup,
function() {
//this is your ready function
}));
I've tested this snippet with video.js 7.4.1 and it works fine. I used video.js's cancel icon instead of text to save space on the control bar. Give it a try:
<script>
var player = videojs('my-player');
var button = videojs.getComponent('Button');
var closeButton = videojs.extend(button, {
constructor: function() {
button.apply(this, arguments);
this.controlText("Exit Course");
this.addClass('vjs-icon-cancel');
},
handleClick: function() {
this.player().dispose();
}
});
videojs.registerComponent('closeButton', closeButton);
player.getChild('controlBar').addChild('closeButton', {});
</script>
var player = videojs('video');
var skipBehindButton = player.controlBar.addChild("button");
var skipBehindButtonDom = skipBehindButton.el();
skipBehindButtonDom.innerHTML = "30<<";
skipBehindButton.addClass("buttonClass");
skipBehindButtonDom.onclick = function(){
skipS3MV(-30);
}
var skipAheadButton = player.controlBar.addChild("button");
var skipAheadButtonDom = skipAheadButton.el();
skipAheadButtonDom.innerHTML = ">>30";
skipAheadButton.addClass("buttonClass");
skipAheadButtonDom.onclick = function(){
skipS3MV(30);
}
function skipS3MV(skipBy) {
player.currentTime(player.currentTime() + skipBy);
}
The reason I've used text ("30<<" and ">>30") is because in my player, the colors are all customizable. So if I used an icon image for skip-back and skip-forward, then I wouldn't be able to change the color of the icon every time someone customizes the player colors (which includes the all the text in the control bar).

Trying to toggle a twitch player on/off using javascript in HTML

So I'm trying to learn some HTML5 stuff for making my own website from scratch. One thing I wanted to try was putting twitch chat and player in the web page. Iwant it to start the page with the player absent and the buttons available to be used to turn the player + chat on or off. Been trying to wrap my head around this and I can't find the solution I'm looking for. Would appreciate any tips or hints on how to do it, thanks!
Display/Hide Player
Display/Hide Chat
<script>
var playeron = false;
function player()
{
if(playeron==false)
{
playeron=true;
document.getElementById("MyPlayer").style.display="block";
}
else
{
playeron=false;
document.getElementById("MyPlayer").style.display="none";
}
}
var chaton=false;
function chat()
{
if(chaton==false)
{
chaton=true;
document.getElementById("MyChat").style.display="block";
}
else
{
chaton=false;
document.getElementById("MyChat").style.display="none";
}
}
</script>
<iframe id = "MyPlayer" src="https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147" width="1280" height="720"></iframe>
<iframe id = "MyChat" src="https://www.twitch.tv/blackdahlia1147/chat?popout=" width="300" height="720"></iframe>
<script>
var playeron=false;
var chaton=false;
function player(){
if(playeron==false){
playeron=true;
document.getElementById("MyPlayer").style.display="block";
}else{
playeron=false;
document.getElementById("MyPlayer").style.display="none";
}
}
//try it yourself for chat
</script>
Display/Hide player
Display/Hide Chat
<style>
iframe{
display:none;
}
</style>
you missed an opening bracket after function twitch(toggle)
Display/Hide Player
Display/Hide Chat
<iframe id="MyPlayer" src="https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147" width="1280" height="720" style="display: block;"></iframe>
<iframe id="MyChat" src="https://www.twitch.tv/blackdahlia1147/chat?popout=" width="300" height="720" style="display: block;"></iframe>
<script>
function toggle(id) {
var elem = document.getElementById(id);
if (elem.style.display != 'none') {
elem.style.display = 'none';
} else {
elem.style.display = 'block';
}
}
</script>
This will work for you, with the advantage of flexibility if you want to make more things to hide/display.
I ran your code and I found that your trying to use variables with links in a if else loop. Now, what I'm saying is you created an option for a loop to search, which is good if you want to create multiple channels for a user to search.
else
{
player = "https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147"
chat = "https://www.twitch.tv/blackdahlia1147/chat?popout="
}
what you first need to do is learn to add a "plugin" into your HTML if you want those two channels only. Your "player" and "chat" are links to a website, a "plugin" is what you're looking for. Go to youtube and type "plugin", when you get your "plugin" then write:
<iframe src="plugin"></iframe>
You really don't need the js at this point.
"Onclick" is what you're also looking for. Go to w3school.com and they have great options of buttons and animation options.

Could an html editor insert jQuery elements?

I've been playing with making an html editor with javascript functions:
So I have a very basic editor with a "bold" button which with I can make whatever text is selected bold, this is fine (I also have a number of other buttons too, but for simplicity and shortness of code I've missed them all out)
<head>
<script>
var editorDoc;
function InitEditable () {
var editor = document.getElementById ("editor");
editorDoc = editor.contentWindow.document;
var editorBody = editorDoc.body;
if ('contentEditable' in editorBody) {
editorBody.contentEditable = true;
}
else {
if ('designMode' in editorDoc) {
editorDoc.designMode = "on";
}
}
}
function ToggleBold () {
editorDoc.execCommand ('bold', false, null);
}
</script>
</head>
<body onload="InitEditable ();">
<button type="button" onclick="ToggleBold ();">Bold</button>
<iframe contenteditable="true" id="editor"></iframe>
</body>
However, something I was really interested in being able to implement would be adding a button which could insert, say, an accordion when pressed
This would then have to add other bits of script (I imagine) to be able to run each accordion (if you had more than one)
Although I haven't had much of a go at doing this myself yet, I was hoping to get a little insight into whether or not it's possible before starting

JS/JQuery text to speech: How to chain audios?

Given n different words:
var text = [ "bèijing Beijing Shanghai"]
var words= [ "bèijing", "Beijing", "Shanghai" ];
Given n different .ogg audio files with a known locations :
<!-- AUDIOS FILES -->
<audio id="id1" src="/audio/Zh-bèijing.ogg"></audio>
<audio id="id2" src="/audio/Zh-Beijing.ogg"></audio>
<audio id="id3" src="/audio/Zh-Shanghai.ogg"></audio>
I use JS getElementById('...').play(), which I run using an onclick event over an HTML element:
<!-- HTML -->
<div id="play" onClick="document.getElementById('id1').play();">
<button>Play</button>
</div>
This allow me to play one audiofile.
Using one single onlick event, how play the first audio, then when done chain to it the play of a second audio ?
Starting fiddles with assets there : http://jsfiddle.net/J9wAB/
Note: I tried document.getElementById('id1').play().done(document.getElementById('id2').play()), but it plays both files simultaneously.
EDIT: I accepted one answer working on Firefox. Yet, this addEventListener based answer fails on on some browsers. An alternative promise base answer may be more successful.
Something like this :
$('#play').data('audio', $('audio:first')).on('click', function() {
var self = this;
$(this).data('audio').on('ended', function() {
var n = $('audio').eq( $(self).data('audio').index('audio') + 1 );
$(self).data('audio', n.length ? n : $('audio:first'));
}).get(0).play();
});
FIDDLE
It gets the first audio element in the document, and stores it in jQuery's data, and once it's played (the onended event) it get's the next audio element in the DOM and the next time the button is clicked, it playes that, and when there are no more audio elements, it starts from the beginning again.
If you really wan't to use the ID instead, it would be something like :
var audio = 1
$('#play').on('click', function() {
$('#id' + audio).get(0).play();
audio++;
});
FIDDLE
To play all three on a single click, one after the other, you'd do
$('#play').on('click', function() {
$('audio').on('ended', function() {
$('audio').eq($(this).index('audio')+1).get(0).play();
}).get(0).play();
});
FIDDLE
No jQuery needed, just listen for the ended event
The simple case is the following:
document.getElementById('id1').addEventListener('ended', function(){
document.getElementById('id2').play();
});
Abstracted, it would look like http://jsfiddle.net/J9wAB/13/
function chain(ids/* id, id, ... */) {
function setHandler(first, next) {
document.getElementById(first).addEventListener('ended', function(){
document.getElementById(next).play();
});
}
for (var i = 0; i < arguments.length - 1; i++) {
setHandler(arguments[i], arguments[i+1]);
}
}
chain('id1', 'id2', 'id3');
You can use the onended="yourcallback()" to start the next audio.
Look at this answer please: https://stackoverflow.com/a/7652194/2707424

How Can I Insert My Javascript Into My Drupal Site/Node

I'm trying to insert a cookie that is provided by a video host that will resume a video where the user left off. They have an example that obviously works. When trying to insert this into my Drupal site, the cookie won't work. The video just starts back at the beginning.
I have enabled "PHP input filter", as I read that I needed to do that for drupal to insert the script. Please see the code that is in my node below.
Can anyone help me figure out why this isn't working, how to get it to work, or a better way of doing this with Drupal?
Thank you,
<script type="text/javascript">
wistiaEmbed.ready( function() {
var all_cookies = document.cookie.split(';'), // gets the value of the cookies on the page
cookie_str = "resume_video=",
resume_cookie = does_resume_cookie_exist(all_cookies);
function does_resume_cookie_exist(cookie_arr) {
var i, curr_string, found;
for (i = 0; i < cookie_arr.length; i++) {
curr_string = cookie_arr[i];
if (curr_string.substring(0,5) === cookie_str.substring(0,5)) {
// we've found it!
found = curr_string;
break;
}
}
return found;
}
function set_cookie_time(t) {
document.cookie = cookie_str + t.toString(); // this takes the time (t) and sets the cookie with that time
}
if (resume_cookie) {
num = resume_cookie.split('=')[1];
start_time = parseInt(num);
wistiaEmbed.time(start_time).play(); // plays the video at the specific time defined in the cookie upon return to the page
} else {
set_cookie_time(0); // places a cookie on the visitor
wistiaEmbed.play(); // starts the video from the beginning
}
wistiaEmbed.bind("timechange", function(t) { // on timechange, reset cookie
set_cookie_time(t);
});
wistiaEmbed.bind("end", function() { // if person has watched the entire video, sets the video to beginning upon retun
set_cookie_time(0);
});
});
</script>
<div id="wistia_npcc5k96s9" class="wistia_embed" style="width:640px;height:508px;"> </div>
<script charset="ISO-8859-1" src="http://fast.wistia.com/assets/external/E-v1.js"> </script>
<script>
wistiaEmbed = Wistia.embed("npcc5k96s9");
</script>**strong text**
What version of drupal are you using? Does the code that you gave actually output in your request response?
There are several solutions to this (IMO).
If the code is showing up in the response, it could be some other javascript error that preventing your code from executing.
If that snippet of code is applicable to all nodes of that type you can use the node_view hook in order to inject your code on that node type, for example (I am assuming D7):
function mymodule_node_view($node, $view_mode)
{
if($node->type =='video_page')
{
drupal_add_js('resume_video.js'); // this js holds your code snippet
}
}
Here's a reference that could help you out
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7
You can similarly inject that snippet of code at the theme layer using a theme hook, probably hook_preprocess https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess/7
Hope that helps.

Categories

Resources