Play button won't start video once video is finished - javascript

I have a play/pause button for a video player im making. Once the video has gone trough one play through, I'd like the play button to have the video start again, but it doesn't.
Here's the script im using:
function play(){
if(!media.paused && !media.ended){
media.pause();
playButton.innerHTML='Play';
window.clearInterval(updateBar);
}else{
media.play();
playButton.innerHTML='Pause';
updateBar=setInterval(update, 100)
}
}

How about structuring your function like this
function play(){
if (!media.paused) { // if currently playing (or ended?)
if (media.ended) { // if at the end
media.currentTime = 0; // go to start
} else { // else
media.pause(); // pause
playButton.innerHTML='Play';
window.clearInterval(updateBar);
return; // and end function here
}
} // then if function didn't end
media.play(); // resume playing
playButton.innerHTML='Pause';
updateBar=setInterval(update, 100);
}
The DOM Interface you're using is HTMLMediaElement.

Related

How to run a function when a html5 video starts playing

i am building an app with ionic, i want to run a function whenever a video starts to play,like hide a button and etc. here's my code
let video = <HTMLVideoElement> document.getElementById(i)
if(video.paused) {
video.play()
video.oncanplay=()=>console.log('Starts playing');
}
The code is not working, please how can i run a function whenever any video on that page starts playing
var vid = document.getElementById("myVideo");
vid.onplay = function() {
alert("The video has started to play");
};
From here: https://www.w3schools.com/tags/av_event_play.asp
Try this, play returns a promise.
const video = document.getElementById("myVideo");
async function playVideo() {
try {
await video.play();
// video is playing, do your stuff here
} catch(err) {
// video is not playing
}
}
if(video.paused) {
playVideo()
}
For more info: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play

AudioContext does not have a pause property?

I have used javascript Audio() before, but now I need to add some reverb effect in the audio and I am using reverb.js which uses the AudioContext api. I have the start property available, but no pause property? How do I pause or stop the audio??
Here is my code:
<script src="http://reverbjs.org/reverb.js"></script>
<script>
// 1) Setup your audio context (once) and extend with Reverb.js.
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
reverbjs.extend(audioContext);
// 2) Load the impulse response; upon load, connect it to the audio output.
var reverbUrl = "http://reverbjs.org/Library/SaintLawrenceChurchMolenbeekWersbeekBelgium.m4a";
var reverbNode = audioContext.createReverbFromUrl(reverbUrl, function() {
reverbNode.connect(audioContext.destination);
});
// 3) Load a test sound; upon load, connect it to the reverb node.
var sourceUrl = "./sample.mp3";
var sourceNode = audioContext.createSourceFromUrl(sourceUrl, function() {
sourceNode.connect(reverbNode);
});
</script>
Play
Stop
Also, I tried using stop(), and it works, but when I fire start() after clicking on stop, the start() doesn't work. Can you you help me out with a solution??
You can use the suspend() and resume() methods of AudioContext to pause and resume your audio: https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/suspend
One way to implement this with a single button for play/pause/resume, would be to add a function that controls the player state. For example:
let started = false;
function pauseOrResume() {
if (!started) {
sourceNode.start();
started = true;
document.getElementById("pauseButton").innerHTML = 'Pause';
} else if (audioContext.state === 'running') {
audioContext.suspend().then(function () {
document.getElementById("pauseButton").innerHTML = 'Resume';
});
} else if (audioContext.state === 'suspended') {
audioContext.resume().then(function () {
document.getElementById("pauseButton").innerHTML = 'Pause';
});
}
}
And replace your existing "Play" button with:
<a id="pauseButton" href="javascript:pauseOrResume()">Play</a>
This does the following:
If the audio hasn't yet been started, the link will say "Play".
If the user clicks "Play", the audio will start playing and the text of the link will change to "Pause".
If the user clicks "Pause" while the audio is playing, it will be paused, and the text of the link will change to "Resume".

how to make button that plays sample of all audio files in page in javascript?

I have code that dynamically loads audio files from a directory. Right now they play/pause when a div is clicked. Here is my javascript doing that:
function get_list_of_files_from_html( html_string ){
var el = document.createElement( 'html' );
el.innerHTML = html_string;
var list_of_files = el.getElementsByTagName( 'a' );
var return_string ='<UL>';
for(var i=5; i < list_of_files.length ; i++){
var current_string = list_of_files[i];
var new_string =
current_string.toString().replace
(/http:\/\/www.website.com\/~user\/programming\//g,'');
var brand_new = new_string.replace('.mp3','');
return_string += '<div class="floating"
onclick="playAudio(\'audio_tag_id'+i+'\')" >'+brand_new+'<audio
id="audio_tag_id'+i+'"> <source src = "'+current_string+'"
type="audio/mpeg"></audio>';
return_string += '</div>';
}
return return_string;
}
function playAudio(tag_id){
var audio= document.getElementById(tag_id);
return audio.paused ? audio.play() : audio.pause();
}
I want to make a button that plays only like five seconds of each audio file and runs through them in order. Does anyone know how I would go about doing this?
You'll need to work asynchronously, so it's a ping-pong between the main code and a callback. Something like this:
// The click event handler
function onPlayClicked(event){
if (!window.HTMLAudioElement){
console.write("Error: no audio");
return;
}
// toggle the state of the playlist not the actual music player
isPlaying = !isPlaying;
if (isPlaying) startPlaying();
else resetList(); // if clicked while playing
}
// sets timer and plays current
function startPlaying(){
if (isPlaying){ // just checking that no one pressed the STOP in the meantime...
setTimout(done, 5000); // timer callback and miliseconds
playAudio();
}
}
// stops this song and starts next. Callback from timer
function done(){
if (nowPlaying == lastSongIndex(){
pauseAudio();
resetPlaylist();
return;
}
if (isPlaying){
pauseAudio();
nowPlaying++;
startPlaying();
}
// plays current audio
function playAudio(){
// Friendly advice: don't use getElementByTag. There may be other 'a's.
audioList = document.getElementById('audiolist');
audioURL = audioList[nowPlaying]; // nowPlaying advanced by done()
urlregex = '/http:\/\/www.website.com\/~user\/programming\//g';
audioData = audioUrl.remove(urlregex).replace('.mp3','');
player = document.getElementById('audioplayer');
player.src = audioData;
player.play();
}
function pauseAudio(){
player = document.getElementById('audioplayer');
player.pause();
}
function reset(){
pauseAudio();
nowPlaying = 0;
isPlaying = false;
// Unpress the button
}
// you can easily fill in the rest.
For understanding the audio control in HTML5 see this for an overview at w3schools, and this as an example on the same website.
Also note friendly remark: Javascript uses camelCase as a convention and not snake_case as in Python.

How to trigger an unpause using audio controls in JavaScript?

Controlling the audio using the following code isn't working. If i click button which onclick calls playpause() it pauses the audio. But on again clicking it isn't resuming.
var audio=new Audio("music.mp3");
function music() {
audio.play();
audio.loop="true";
}
function playpause() {
if(audio.play)
{
audio.pause();
}
else if(audio.pause)
{
audio.play();
}
}
However if i use following, It is enabling pause and play using the same button
var audio=new Audio("music.mp3");
function music() {
audio.play();
audio.loop="true";
}
var count=0;
function playpause() {
if(count%2==0)
{
audio.pause();
}
else
{
audio.play();
}
count++;
}
What's wrong with the 1st one?
The HTML5 audio tag doesn't provide a 'play' property like you are trying to use in your code but it does provide a 'paused' property which by calling it returns the opposite Boolean. You would need to use it to query the state of the audio element.
Like this:
If(audio.paused) {
audio.play();
}
else {
audio.pause();
}

Play and Pause with onclick on the same Img

The following script is playing a soundfile when i click on a img (onclick). How do i pause it by clicking on the same img? I´ve tried audio.pause(), but it won´t work.
function play(){
var audio = document.getElementById("myaudio");
audio.style.display="block";
audio.play();
}
<img src="Bilder/play2.png">
You should rename your function to audioHandler() for example which will handle whether to play or pause your audio.
Create a boolean to remember if your audio was playing or was on pause.
//initial status: audio is not playing
var status = false;
var audio = document.getElementById("myaudio");
function audioHandler(){
if(status == false || audio.paused){
audio.play();
status = true;
}else{
audio.pause();
status = false;
}
}
Check the media.paused property of your HTMLMediaElement
function play_pause(media) {
if (media.paused) {
media.play();
else {
media.pause();
}
}
Use this in the handler on the element you want to control the action
var elm = document.getElementById('play_button'),
audio = document.getElementById('myaudio');
elm.addEventListener('click', function (e) {
play_pause(audio);
});

Categories