I'm trying to build a simple HTML5 music player with JavaScript.
I've build a player with this code:
<audio controls="controls">
<source id="song" src="horse.ogg" type="audio/ogg">
</audio>
I've build a couple of <a> which call function changeSong(n);
function changeSong(n) {
document.getElementById("song").src = "song" + n + ".mp3";
}
and when I click the <a>'s nothing happens to the document, and it won't work..
The <a>'s:
Play song 1 </br>
Play song 2
What do to make it work?
////
I tried just running the JavaScript w/o function and it works. but when it's called from the as a function it doesn't...
Change:
Play song 2
With:
Play song 2
Is that a typo?
Actually, it works in the console:
document.getElementById("song");
<source id="song" src="horse.ogg" type="audio/ogg">
document.getElementById("song").src;
"chrome://newtab/horse.ogg"
document.getElementById("song").src = 'Hi.ogg';
"Hi.ogg"
document.getElementById("song").src;
"chrome://newtab/Hi.ogg"
You miss the name of the method in the call. This works:
Play song 1 </br>
Play song 2
what is your goal ? Do not tell me that you are trying to call the
changeSong(1)
on the "Play song 1" click.
just by reading your code I can say that change
Play song 2
by
Play song 2
Or I'm missing something :/
Can you add some debug code into the
changeSong(n){
document.getElementById("song").src="song"+n+".mp3";
}
an tell us if something is appening :)
I'm not familiar with HTML5 , but I can find two errors.
You're calling playSong instead of changeSong
You should declare that changeSong is a function:
function changeSong(n){
document.getElementById("song").src = "song" + n + ".mp3";
}
Related
This question already has answers here:
How to autoplay audio in any browser?
(2 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I want to play audio every second as it is clock so wanted to insert a ticking sound .
Is there any way to achieve that without a trigger as clock should always be automatic .
Here is code which works on trigger and running:
<audio id="audiotag1" src="Sounds\clock tick.mp3" preload="metadata" controls></audio>
<button onclick="trigger()">Start</button>
function trigger(){
setInterval(clockRunner, 1000);
function clockRunner(){
var audioElement = document.getElementById('audiotag1');
audioElement.play();
}
}
Here is code which is without trigger but not running :
setInterval(clockRunner, 1000);
function clockRunner() {
var audioElement = document.getElementById('audiotag1');
audioElement.play();
}
<audio id="audiotag1" src="Sounds\clock tick.mp3" preload="metadata" controls></audio>
Error showing is :
Uncaught DOMException: play() failed because the user didn't interact with the document first.
Here is the question referring to the problem(Error) but solution provided is for video and they can be play muted and have visual content
Thanks for help in advance
You cannot use document.getElementById (audio element) and js together to just use it and .play, that doesnt work, but this should
function play() {
var audio = new Audio('Sounds\clock tick.mp3');
audio.play();
}
setInterval(play, 1000)
In the string just use your source. :)
I would like to say this is worth a shot
<audio id="audiotag1" preload="metadata" controls>
<source src="Sounds\clock tick.mp3" type="audio/mpeg">
</audio>
<button onclick="triger()">Start</button>
Also wanna mention you have a type, where it says audioElement.play
you put an extra space, making it audioElement .play which could have thrown an error.
Looks like there's a relevant post that just popped up. (Source:
https://stackoverflow.com/a/62720714/9303612)
A couple of weeks ago I tried exactly what you intend to do, however,
after a lot of research I realized this is nearly impossible now. For
example in Chrome (I don't know if also in other browsers) you cannot
autoplay sounds/videos unless one of these points is accomplished:
The user interacts with your website (click on any part of your site).
The user added your website to the home screen (mobile).
The user has crossed the media interaction index (MEI) threshold.
Your website is in the Google whitelist for autoplaying (such as Youtube).
I'm working on a page that, on my client's request, loads playing a background soundtrack.
Of course it's just for those users who are not navigating with audio autoplay disabled.
So the simple piece of code used to start playing the music is something like the following:
<audio autoplay id="background-soundtrack">
<source src="mytrack.mp3" type="audio/mpeg">
</audio>
I'd like to make music stop (even better: make it fade out in a matter of a few seconds) as soon as the user clicks anywhere on the page -- it should work tapping on mobile devices too.
Can you please suggesitng me a smart way to achieve my goal?
It doesn't matter if it's pure JavaScript or jQuery.
Thanks!
try this jquery:
$('document').on('click','body',function(){
if ($('#background-soundtrack').paused == false){
$('#background-soundtrack').animate({volume: 0}, 1500,
//1500 duration time
function(){
$('#background-soundtrack').pause()
});
}
});
The HTML5 audio elements has the pause method, that you can use at "onClick" (work in touch too) event on body, document, window...
Like this (I delete the "-" in id):
document.onclick = function(e){
backgroundsoundtrack.pause();
}
<audio autoplay id="backgroundsoundtrack">
<source src="mytrack.mp3" type="audio/mpeg">
</audio>
I'm trying to design my own audio player.
I made "play", "pause" and "stop" symbols (Png format) and I couldn't find a solution to actually ad play pause and stop functions when you click on them.
I figured out how to play sound when the word "play" is clicked (no button) but I'm lost when it comes to add "pause" or "stop".
I'm a rookie using html/css so please forgive me if I'm not very clear.
This is what I have so far:
<audio id="audio" src="sons/son.mp3" autostart="false" ></audio>
<a onclick="PlaySound()"> Play </a>
<script>
function PlaySound() {
var sound = document.getElementById("audio");
sound.play()
}
</script>
Thank you for your answers.
you were on the right way to achieve this !
At first you declare globally your variable sound to get it from your three functions. To pause your sound you use the .pause() method and to stop it you return to 0 second playback time with the .currentTime property.
The code:
<audio id="audio" src="sound.mp3" autostart="false" ></audio>
Play
Pause
Stop
<script>
const sound = document.getElementById("audio")
function PlaySound() {
sound.play()
}
function PauseSound(){
sound.pause()
}
function StopSound(){
sound.pause()
sound.currentTime = 0
}
</script>
Hope it helps you !
Here is an example code:
Link 1
Link 2
Link 3
<audio>
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
Here is a fiddle with the example code that I provided:
https://jsfiddle.net/qkuLkqao/2/
All the examples that I found use mouseover, my version would be simpler than this, playing a sound file when the user clicks on a certain link.
How can I achieve this?
I did some research on SO and Google but I couldn't find anything related (most probably I didn't searched correctly).
You can use js to manipulate the audio element...
let audio = document.getElementById("audio");
let link = document.getElementById("audioLink");
link.onclick = () => {
audio.play();
};
<a id="audioLink" href="#">Link 1</a>
Link 2
Link 3
<audio id="audio">
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
Take in to consideration that a link element is not mean to be a audio button.. you can use a button element instead..
Please try that.
document.querySelectorAll('a')[0].addEventListener('click', player, false)
function player() {
document.querySelector('audio').play()
}
This is made to play on Link 1.
You can declare use onclick on a tag and call a function to play the file.
Note. You can add the src path of the audio file as any data property in a tag and use it to play the related audio file
function playThis (el) {
if(window.audio) {
audio.pause();
}
window.audio = new Audio (el.getAttribute("data-src"));
window.audio.play();
}
Link 1
Link 2
Link 3
var links = document.getElementsByTagName('a'),
audio = document.getElementById('a-on-click'),
clickHandler = function () {
audio.play();
}
;
for (var i in links) {
links[i].addEventListener('click', clickHandler);
}
https://jsfiddle.net/qkuLkqao/14/
I have a html 5 video on a page like this:
<video preload="none" id="movie" poster="http://my_poster_url.com/sourcefile.jpeg" controls>
<source id="mp4" type="video/mp4" src="http://my_mp4.com/sourcefile.mp4"></source>
<source id="webm" type="video/webm" src="http://my_webm.com/sourcefile.webm"></source>
</video>
Below that video I have a navigation where you can skip to different times in the video. It works perfectly when the video is playing, but when paused following error occurs:
InvalidStateError: An attempt was made to use an object that is not,
or is no longer, usable
Here the function:
$('#my_video_navigation a').click(function () {
var start_in_seconds=...//a variable that gets the time from a json based on the navigation index
$("#movie").get(0).currentTime = start_in_seconds;
$("#movie").get(0).play();
}
I added an if/else statement wether the video is paused or not:
if ($('#movie').get(0).paused) {
$("#movie").get(0).play();
}
and then tried to set the current time like above and even with a set timeout function so that it will wait till the video loaded and is playing but that didn't work. What am I doing wrong or what did I forget?
You should change the currentTime field of the media element, as you can see here in the API doc. There is also an example code here, at MDN
For reference, the sample code there:
var mediaElement = document.getElementById('mediaElementID');
mediaElement.seekable.start(); // Returns the starting time (in seconds)
mediaElement.seekable.end(); // Returns the ending time (in seconds)
mediaElement.currentTime = 122; // Seek to 122 seconds
mediaElement.played.end(); // Returns the number of seconds the browser has played
where the mediaElementID is the id of the audio or video tag.
Edit: It seems I've misread your question. I will take a further look.