Audio pause/play with JS variable (ubernewb) - javascript

I'm working on a simple project that includes a media (mp3) player in the sidebar. I can get the play/pause button to visually switch and I can turn off the audio by assigning a href to another image however when trying to get the swapped image to pause audio I just can't seem to figure it out, here's my code..
EDIT: deleted shotty code
EDIT: Figured out three ways to do this, the two kind people below posted great ways but I also figured out how to crudely do this via jquery.
$('#left-05-pause_').click(function(){
$('#left-05-pause_').hide();
$('#left-05-play_').show();
});
$('#left-06-audio_').click(function(){
audio.volume = 1;
$('#left-06-audio_').hide();
$('#left-06-mute_').show();
});

Mitch, I have three points for you:
there's no need to wrap <a> around <img>
for performance avoid overuse of selecting elements (like getElementById), because once you've selected a link to the element put it into a variable and use again to access the same element
use native info about element's state (for <audio> in this example) - explore its properties
All in all just try next sample (file names have been changed for clarity):
<body>
<audio id="audioId">
<source src="song.mp3" type="audio/mp3" />
</audio>
<img id="imageId" src="play.png" onclick="toggle()" />
<script>
var audio = document.getElementById( 'audioId' )
, image = document.getElementById( 'imageId' )
function toggle()
{
if ( audio.paused )
{
image.src = 'pause.png'
audio.play()
}
else
{
image.src = 'play.png'
audio.pause()
}
}
</script>
</body>

You can try this
<a href="#">
<img src="http://royaltrax.com/aadev/images/left/images/left_05.png" id="imgPauseChange" onclick="changeImage()">
</a>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgPauseChange").src == "http://royaltrax.com/aadev/images/left/images/left_05.png")
{
document.getElementById("aud").play();
document.getElementById("imgPauseChange").src = "http://royaltrax.com/aadev/images/left/images/left_05-pause.png";
}
else
{
document.getElementById("aud").pause();
document.getElementById("imgPauseChange").src = "http://royaltrax.com/aadev/images/left/images/left_05.png";
}
}
</script>

Related

HTML <track> element shows cues in console but also length = 0 and they cannot be accessed by indexing

I'm working on a page with a video player in which I'm trying to show vtt captions and get information from the cues in the <track> element.
Here's what's relevant for the player in HTML:
<div class="video">
<video id="vid">
<source src="Video.mp4" type="video/mp4">
<track kind="subtitles" src="Captions.vtt" srclang="en">
</video>
</div>
I had something like this in my JavaScript first, just to see what I was getting before manipulating anything in code.
var trackObject = $('track')[0].track;
trackObject.mode = 'showing';
console.log('Track cues:');
console.log(trackObject.cues);
console.log(trackObject.cues[0]);
The change to the mode attribute is done there because, if I set default to the <track> element in HTML, then the video doesn't appear in many browsers. Still don't know why.
What this prints to the console is the following:
However, when I expand the TextTrackCueList, I do see the cues:
This has only made sense to me if I assume that the cues have loaded into the element, but the length attribute hasn't been updated. But I still don't know what's that length I'm seeing at the end of the list, which shows the actual number of cues.
I haven't found any kind of load event on the text track, so this is what I did to make sure I can get the cues:
var trackObject = $('track')[0].track;
trackObject.mode = 'showing';
var waitForCues = setInterval(function() {
if (trackObject.cues.length > 0) {
var cueList = getTracks(trackObject)
// ...Do some processing with the cues...
clearInterval(waitForCues);
}
}, 40);
Why does this happen with the length attribute of the track element? How can I get rid of that waiting for the length to be greater than 0?
As an HTMLMediaElement, the <track> element supports the same global load and error events that any other HTMLElement does, so you can listen for those to determine whether your VTT is ready for business or not.
mytrack.addEventListener(`load`, evt => {
console.log(`good to go`);
const { track } = mytrack;
// force this track to become active so we can get the cues:
track.mode = "showing";
const { cues } = track;
console.log(`${cues.length} cues found`);
});
mytrack.addEventListener(`error`, evt => {
console.log(`yeah that's a problem`);
});
<video controls>
<source src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" type="video/mp4">
<track
id="mytrack"
kind="captions"
src="data:text/plain;charset=utf-8,WEBVTT%0A%0A00%3A00%3A00.500%20--%3E%2000%3A00%3A02.000%0AThe%20Web%20is%20always%20changing%0A%0A00%3A00%3A02.500%20--%3E%2000%3A00%3A04.300%0Aand%20the%20way%20we%20access%20it%20is%20changing"
srclang="en"
label="English"
default="default">
>
</video>

Javascript, dynamically change Video-Url - Video URL is set / Just Placeholder Poster Shown

i want to dynamically change the Urls of two Videos. My Problem is that the first Video's URL is getting Changed and plays correctly and the second Video just changes the Videos-Url without Playing it. The Second Video still shows the Placeholder-Poster.
Without changing the Video.source.src my Page looks like This:
<div class="container-fluid" id="container">
<div class="cocoen">
<video loop autoplay muted poster="img/placeholder_0.png">
<source type="video/mp4">
</video>
<video loop autoplay muted poster="img/placeholder_1.png">
<source type="video/mp4">
</video>
</div>
When trying to set the Video-Sources (yes, i know that both video-urls are the same, its just for test purposes :p)
var urls = ["img/small_1.mp4", "img/small_1.mp4"];
var sources = $("video > source").toArray();
sources[0].src = urls[0];
sources[1].src = urls[1];
startVideos();
Only the first (left) one is working:
But the Sources are correctly set on both videos.
I want to change the URLS more then Once, so just setting the URLS in the HTML isnt an Option.
If i set the src of video#1 to movie1 in html and video#2.src to movie2
and use JS to set video#1.src = movie2 and video#2.src=movie1
only the left video changes in display even tho the html has the correct src's.
I dont know if this Information is important, but this is how i start the Videos, after i set the URLS:
function reduceRetryOnError(array, callbackFunction, functionToRetry) {
success = array.reduce((acc, value) => acc && callbackFunction(value));
if (!success) {
console.log("Reduce failed: Retry in 300 ms");
setTimeout(functionToRetry(), 300);
}
}
function startVideos() {
function startVideo(video) {
if (!video) {
return false;
}
if (video.paused) {
video.play();
}
return true;
}
reduceRetryOnError($("video").toArray(), startVideo, startVideos);
}
I also tried to Pause and the start the Video again within the Starting Function.
Ty in advanced.

player.stop() dosen 't works on videojs

I'm trying to implement videojs with the IMA plugin, and i need to capture the stop and play event from a button outside the videobox in my react app.
The thing is i capture the event on my buttons and works fine, but they dosen t work when i want to stop the ADS.. why? Any clue?
i use this example
https://googleads.github.io/videojs-ima/examples/simple/
and i log the player.ima and return this, but i cant access to any element..
here is my code! thanks!
index.js
<video id="content_video"
class="video-js vjs-default-skin""
controls
>
<source src="//commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" ></source>
</video>
<script>
window.player = videojs
var player = window.player('content_video');
var options = {
id: 'content_video',
adTagUrl: 'http://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/ad_rule_samples&ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&output=xml_vmap1&unviewed_position_start=1&cust_params=sample_ar%3Dpremidpostpod%26deployment%3Dgmf-js&cmsid=496&vid=short_onecue&correlator='
};
player.ima(options);
</script>
home.js
handlePlay = () => {
if(this.props.showPlay == 'block'){
const player = window.videojs(`#content_video`)
player.play() //only work on the video not in ads
} else {
const player = window.videojs(`#content_video`)
player.pause() //only work on the video not in ads
}
}

how to add Mute/Un-mute button

I'm trying to add a mute/un-mute button to my website. I created a panoramic tour using a program called Panotour by Kolor. Thing is I exported it as HTML but can't seem to find the audio tags or anything. I found the file which contains the audio files, I just need a way to mute the music.
.
Here's what I'v done so far.
<div>
<img class="img-responsive" src="Images/muteon.png" id="mute" onclick="toggleSound(this);">
</div>
<script>
function toggleSound(img)
{
if(img.src.match(/blank/))
{
console.log('black');
img.src = "Images/muteon.png";
}
else
{
console.log('blank');
img.src = "Images/muteoff.png";
}
}
</script>

change <audio> src with javascript

I have multiple audio files that I want to stream based on the user selects. How do I do that? This is what I have so far and it doesn't seem to work.
*UPDATE: Made a few changes and now its claiming that audio.load(); is not a function. Can anyone tell me why that is? The Code is updated to reflect the changes.
JavaScript:
function updateSource(){
var audio = document.getElementById('oggSource');
audio.src =
'audio/ogg/' +
document.getElementById('song1').getAttribute('data-value');
audio.load();
}
HTML:
<audio id="audio" controls="controls">
<source id="oggSource" src="" type="audio/ogg"></source>
<source id="mp3Source" type="audio/mp3"></source>
Your browser does not support the audio format.
</audio>
<ul style="list-style: none">
<li>Sunday May 27, 2012
<ul style="display: none">
<li id="song1" data-value="song1.ogg">
<button onclick="updateSource();">Item1</button>
</li>
<li>Item2</li>
<li>Item3</li>
</ul>
</li>
</ul>
Item2 and Item3 I will want to play a different audio file when they are clicked on.
Try this snippet
list.onclick = function(e) {
e.preventDefault();
var elm = e.target;
var audio = document.getElementById('audio');
var source = document.getElementById('audioSource');
source.src = elm.getAttribute('data-value');
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
};
<ul style="list-style: none">
<li>Audio Files
<ul id="list">
<li>Death_Becomes_Fur.oga</li>
<li>Death_Becomes_Fur.mp4</li>
<li>rrs006.oga</li>
<li>sound_90.mp3</li>
</ul>
</li>
</ul>
<audio id="audio" controls="controls">
<source id="audioSource" src=""></source>
Your browser does not support the audio format.
</audio>
JSFiddle http://jsfiddle.net/jm6ky/2/
with jQuery:
$("#playerSource").attr("src", "new_src");
var audio = $("#player");
audio[0].pause();
audio[0].load();//suspends and restores all audio element
if (isAutoplay)
audio[0].play();
If you are storing metadata in a tag use data attributes eg.
<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>
Now use the attribute to get the name of the song
var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();
Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution.
Using componentWillReceiveProps I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilĂ .
#propTypes =
element: React.PropTypes.shape({
version: React.PropTypes.number
params:
React.PropTypes.shape(
url: React.PropTypes.string.isRequired
filename: React.PropTypes.string.isRequired
title: React.PropTypes.string.isRequired
ext: React.PropTypes.string.isRequired
).isRequired
}).isRequired
componentWillReceiveProps: (nextProps) ->
element = ReactDOM.findDOMNode(this)
audio = element.querySelector('audio')
source = audio.querySelector('source')
# When the url changes, we refresh the component manually so it reloads the loaded file
if nextProps.element.params?.filename? and
nextProps.element.params.url isnt #props.element.params.url
source.src = nextProps.element.params.url
audio.load()
I had to do it this way, because even a change of state or a force redraw didn't work.
Found this spec note for those trying to change the src of a source element. Especially useful for libs like React where audio.load() causes render loop.
..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
<audio>
<source src='./first-src'/>
</audio>
To change the src
<audio src='./second-src'/>
<source src='./first-src'/>
</audio>
Try this:
Replace:
audio.load();
with:
audio.play();
change this
audio.src='audio/ogg/' + document.getElementById(song1.ogg);
to
audio.src='audio/ogg/' + document.getElementById('song1');

Categories

Resources