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');
Related
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>
I am making a mental health website in which there is a meditation area. there are two div cards and inside of each, there is one button that plays and stops music when clicked.
I am using script tags inside the html file for extra information.
Purpose:
when the buttons inside each of the two card div is clicked, a guided meditation audio should play.
there is a long audio and a short audio that comes in two formats of mp3 and ogg.
Problem:
one of the audios play perfectly but the second one doesn't work. meaning it wont play and stop when the button is clicked.
can you please check and tell me what's wrong.
<div class="main-box">
<div class="slot1">
<p class="line line1">this is the long music</p>
<audio id=rollSound loop>
<source src="sounds/long-medi.mp3" type="audio/mpeg">
<source src="sounds/long-medi.ogg" type="audio/ogg">
Your browser does not support the sound files. Please proceed by using other solutions.
<!--the obove text will only show if the users' browser does not play the two files. -->
</audio>
<button id=play>play/stop</button>
<script>
const rollSound = document.getElementById('rollSound');
const btn = document.getElementById('play');
btn.addEventListener("click", e => rollSound.paused ? rollSound.play() : rollSound.pause());
</script>
</div>
<div class="slot2">
<p class="line line2">this is for short music</p>
<audio id=shortsound loop>
<source src="sounds/short-medi.mp3" type="audio/mpeg">
<source src="sounds/short-medi.ogg" type="audio/ogg">
Your browser does not support the sound files. Please proceed by using other solutions.
</audio>
<button id=roll>play/stop</button>
<script>
const shortsound = document.getElementById('shortsound');
const btn = document.getElementById('roll');
btn.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());
</script>
</div>
There is an error when executing your script because you can not declare var btn = a second time.
Instead change the following
const shortsound = document.getElementById('shortsound');
const btn = document.getElementById('roll');
btn.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());
to something like this:
const shortsound = document.getElementById('shortsound');
const btn2 = document.getElementById('roll');
btn2.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());
and it will work, see this jsfiddle:
https://jsfiddle.net/snw3950L/1/
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.
I use the HTML video element. As source I use a .mp4 video with sound. On my video element there are a few attributes. Default I use the attribute muted so there is no sound. With some JavaScript I add or remove the attribute muted by clicking on a button. So this works, when I inspect my markup and click the button I can see how the attribute muted will be added or removed (check out my snippet below).
My problem is, that when removing it, there is no sound. If I start the video file in an video player on my laptop or open it directly in the browser, I can hear the sound. Due to many posts, it should be possible to toggle the sound with this solution. I don't know why it doesn't have sound only when I use it in my video element with adding/removing the attribute muted. Any ideas?
const $ctx = $('.video');
const $video = $ctx.find('.video__video');
const $toggleSound = $ctx.find('.video__toggle-sound');
$toggleSound.click(this.handleVideoSound.bind(this));
function handleVideoSound() {
const attr = $video.attr('muted');
if (typeof attr !== typeof undefined && attr !== false) {
$video.removeAttr('muted');
} else {
$video.attr('muted', '');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video">
<video class="video__video" autoplay loop muted playsinline poster="/assets/img/video-poster.png">
<source src="/assets/video/video.mp4" type="video/mp4">
</video>
<button class="video__toggle-sound">Toggle video sound</button>
</div>
Replace your handleVideoSound method with the below code
function handleVideoSound() {
const attr = $video.prop("muted");
$video.prop("muted", !attr);
}
Hope it will help you. Below is the working code snippet.
const $ctx = $(".video");
const $video = $ctx.find(".video__video");
const $toggleSound = $ctx.find(".video__toggle-sound");
$toggleSound.click(this.handleVideoSound.bind(this));
function handleVideoSound() {
const attr = $video.prop("muted");
$video.prop("muted", !attr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video">
<video class="video__video" autoplay loop muted playsinline poster="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg">
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", type="video/mp4" />
</video>
<button class="video__toggle-sound">Toggle video sound</button>
</div>
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>