i have this code in javascript .. i want it to work in every single song in my songs variable ..any help on how to do it
thanks
window.addEventListener("load", () => {
let songs = document.querySelectorAll(".song");
let sections = document.querySelectorAll(".section button");
//song start play
sections.forEach((button, index) => {
button.addEventListener("click", function () {
if(songs[index].paused){
songs[index].play();
} else{
songs[index].pause();
}
});
});
});
On button click, if the song is at pause, play it... But you also need to makes sure all other songs are paused.
You just need an additional forEach loop to pause them all before playing the one associated with the clicked button.
window.addEventListener("load", () => {
let songs = document.querySelectorAll(".song");
let sections = document.querySelectorAll(".section button");
//song start play
sections.forEach((button, index) => {
button.addEventListener("click", function () {
if(songs[index].paused){
songs.forEach(song => song.pause()) // This will pause all songs
songs[index].play();
} else{
songs[index].pause();
}
});
});
});
audio{
display: none;
}
button{
margin: 0.5em;
}
<div class="section">
<audio controls class="song" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"></audio>
<button class="button">Play song #1</button>
</div>
<div class="section">
<audio controls class="song" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"></audio>
<button class="button">Play song #2</button>
</div>
<div class="section">
<audio controls class="song" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"></audio>
<button class="button">Play song #3</button>
</div>
Related
I am still newbie
I'm studying,
help if you can I don't understand, I want to add 2 3 songs to the site I wrote the code but only 1 song works
how to make all songs play
but not simultaneously, but in turn,
For example
I am listening to music 1 and then I want to listen to play 2, when I press play 2, play 1 should stop
how to do it i don't understand can you help in advance thanks
I'll leave the code
var mySong = document.getElementById("mySong");
var icon = document.getElementById("icon");
icon.onclick = function() {
if(mySong.paused){
mySong.play();
icon.src = "img/pause-icon.png";
}else{
mySong.pause();
icon.src = "img/play-icon.jpg";
}
}
<img src="img/play-icon.jpg" alt="" id="icon" width="80">
<audio id="mySong">
<source src="Ганвест - Кайфули.mp3" type="audio/mp3">
</audio>
<img src="img/play-icon.jpg" alt="" id="icon" width="80">
<audio id="mySong">
<source src="Ганвест - Кайфули.mp3" type="audio/mp3">
</audio>
You need unique IDs or delegate, then you do not need IDs at all:
Note I changed icon id to icon class, wrapped each song in a div and all songs in a div too
const icons = {
play: "https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png",
pause: "https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/play-pause.png"
}
const isPlaying = audioElement => !audioElement.paused;
const container = document.getElementById("songs");
const songs = container.querySelectorAll(".song audio");
const controls = container.querySelectorAll(".song .icon");
container.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.matches(".icon")) {
const mySong = tgt.closest(".song").querySelector("audio");
// pause all other songs
songs.forEach((song,i) => {
if (isPlaying(song) && song != mySong) {
song.pause()
controls[i].src=icons.play;
}
});
if (mySong.paused) {
mySong.play();
tgt.src = icons.pause;
} else {
mySong.pause();
tgt.src = icons.play;
}
}
})
<div id="songs">
<div class="song">
<img src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png" alt="Toggle" class="icon" width="80">
<audio id="mySong1">
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mp3"></audio>
</div>
<div class="song">
<img src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png" alt="Toggle" class="icon" width="80">
<audio id="mySong2">
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" type="audio/mp3"></audio>
</div>
</div>
I am trying to add play/pause toggle functionality to a single button for an mp3 player project where the play button will turn to a "||" icon when music is playing and will revert to the play button when the music is paused by only using vanilla JavaScript. I have tried implementing an if-else statement which seems to be commonly used for this type of functionality, but the icon will only change to the "||" icon when the song is played, but will not pause and change to the play icon when clicked again. I have tried creating a separate function for the task of pausing the song, but still not getting the desired result.
var playButton = document.querySelector('#play-button');
var songArtist = document.querySelector('.song-artist');
var songTitle = document.querySelector('.song-name');
var stateIcon = document.querySelector('#stateicon');
var trackList = [ {
'Songartist': 'Artist1',
'Songtitle': 'Dance',
'songfile': 'Dance.mp3'
},
{
'Songartist': 'Artist2',
'Songtitle': 'Fight',
'songfile': 'Battle.mp3'
}
];
var currentSong = 0;
var song = new Audio();
function playSong() {
song.src = trackList[currentSong].songfile;
songArtist.innerText = trackList[currentSong].Songartist;
songTitle.innerText = trackList[currentSong].Songtitle;
if (song.paused) {
stateIcon.className = 'fas fa-pause';
song.play();
} else {
stateIcon.className = 'fas fa-play';
song.pause();
}
}
<body>
<div class="screen">
<div class="song-info-text">
<p class="song-artist">Some text</p>
<p class="song-name">Some more text</p>
</div>
</div>
<div class="mp3-buttons">
<button class="button" type="button" name="button"><i class="fas fa-step-backward"></i></button>
<button id="play-button" onclick="playSong()"><i id="stateicon" class="fas fa-play"></i></button>
<button onclick="nextSong()" class="button" type="button" name="button"><i class="fas fa-step-forward"></i></button>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
The snipped provided is incomplete (no element has the class "song-artist", for one). I'd suggest looking at your javascript dev console for any errors, first. Otherwise, it could be that setting the src of your audio element is resetting your audio's play state. You could try only setting the src if it's different from that of the current track.
Basically I'm working on a drum machine project and I need each out of 9 buttons that will be showed on the screen to be clickable with the mouse click as well as by a related keyboard key.
Setting it up to work with mouse with onClick event attached to each button click was pretty straightforward, but I'm having difficulties with making it to work with the keyboard.
So far I have done the following:
1) Set up componentDidMount() with an event listener to read each key press:
componentDidMount() {
const setKey = (event) => { this.setState({ keyPressed: event.key.toUpperCase() }) }
document.addEventListener('keydown', setKey);
}
2) Set up componentDidUpdate() to check whether a currently pressed key is among keys that are used in the app, then it triggers handleClick function and passes couple arguments:
componentDidUpdate() {
if (this.state.keyList.includes(this.state.keyPressed)) {
this.handleClick("keydown", this.state.keyPressed)
}
}
3) Finally, handleClick checks whether it is a "keydown" or "click" event and plays the corresponding <audio>:
handleClick(event) {
if (arguments[0] === "keydown") {
var audio = document.getElementById(arguments[1])
} else {
const { name, value } = event.target
this.setState({
displayValue: value
})
var audio = document.getElementById(name)
}
audio.paused ? audio.play() : audio.currentTime = 0
}
My code is currently able to play corresponding audio for both scenarios, but I'm not sure how to make it display a corresponding value from the button in case when it is triggered by a keyboard button since I can't figure out how to pass event.target as it is done for onClick scenario.
Also, probably the main issue, is that eventually I would like to set up CSS and Bootstrap for this project and the button should be changing it's color when it is played, as well as when it is triggered by the keyboard. What I have done right now is rather a workaround and when the time comes to set it up, it won't be working this way.
Is there anyway I could trigger buttons when a corresponding keyboard keys are pressed and behave in a way as it would when I do it via onClick?
class App extends React.Component {
constructor() {
super()
this.state = {
displayValue: "",
keyPressed: "",
keyList: ["Q", "W", "E", "A", "S", "D", "Z", "X", "C"]
}
this.handleClick = this.handleClick.bind(this)
}
componentDidMount() {
const setKey = (event) => { this.setState({ keyPressed: event.key.toUpperCase() }) }
document.addEventListener('keydown', setKey)
}
componentDidUpdate() {
if (this.state.keyList.includes(this.state.keyPressed)) {
this.handleClick("keydown", this.state.keyPressed)
}
}
handleClick(event) {
if (arguments[0] === "keydown") {
var audio = document.getElementById(arguments[1])
} else {
const { name, value } = event.target
this.setState({
displayValue: value
})
var audio = document.getElementById(name)
}
audio.paused ? audio.play() : audio.currentTime = 0
}
render() {
return (
<div id="drum-machine">
<div id="display">{this.state.displayValue}</div>
<div className="drum-pad" id="pad-q">
<button type="button" name={this.state.keyList[0]} value="Chord 1" onClick={this.handleClick}>Q</button>
<audio className="clip" id={this.state.keyList[0]} src="https://s3.amazonaws.com/freecodecamp/drums/Chord_1.mp3"/>
</div>
<div className="drum-pad" id="pad-w">
<button type="button" name={this.state.keyList[1]} value="Chord 2" onClick={this.handleClick}>W</button>
<audio className="clip" id={this.state.keyList[1]} src="https://s3.amazonaws.com/freecodecamp/drums/Chord_2.mp3"/>
</div>
<div className="drum-pad" id="pad-e">
<button type="button" name={this.state.keyList[2]} value="Chord 3" onClick={this.handleClick}>E</button>
<audio className="clip" id={this.state.keyList[2]} src="https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3"/>
</div>
<div className="drum-pad" id="pad-a">
<button type="button" name={this.state.keyList[3]} value="Shaker" onClick={this.handleClick}>A</button>
<audio className="clip" id={this.state.keyList[3]} src="https://s3.amazonaws.com/freecodecamp/drums/Give_us_a_light.mp3"/>
</div>
<div className="drum-pad" id="pad-s">
<button type="button" name={this.state.keyList[4]} value="Open HH" onClick={this.handleClick}>S</button>
<audio className="clip" id={this.state.keyList[4]} src="https://s3.amazonaws.com/freecodecamp/drums/Dry_Ohh.mp3"/>
</div>
<div className="drum-pad" id="pad-d">
<button type="button" name={this.state.keyList[5]} value="Closed HH" onClick={this.handleClick}>D</button>
<audio className="clip" id={this.state.keyList[5]} src="https://s3.amazonaws.com/freecodecamp/drums/Bld_H1.mp3"/>
</div>
<div className="drum-pad" id="pad-z">
<button type="button" name={this.state.keyList[6]} value="Punchy Kick" onClick={this.handleClick}>Z</button>
<audio className="clip" id={this.state.keyList[6]} src="https://s3.amazonaws.com/freecodecamp/drums/punchy_kick_1.mp3"/>
</div>
<div className="drum-pad" id="pad-x">
<button type="button" name={this.state.keyList[7]} value="Side Stick" onClick={this.handleClick}>X</button>
<audio className="clip" id={this.state.keyList[7]} src="https://s3.amazonaws.com/freecodecamp/drums/side_stick_1.mp3"/>
</div>
<div className="drum-pad" id="pad-c">
<button type="button" name={this.state.keyList[8]} value="Snare" onClick={this.handleClick}>C</button>
<audio className="clip" id={this.state.keyList[8]} src="https://s3.amazonaws.com/freecodecamp/drums/Brk_Snr.mp3"/>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.1/umd/react-dom.production.min.js"></script>
<body>
<div id="root"></div>
</body>
I'm attempting to add a play/pause button to a Wistia hosted video. I have it mostly working however when I add in multiple videos it's not targeting the current video. Instead when I click on the second video the first video plays.
Below is the HTML:
<div class="tqm-video-wrapper">
<div class="tqm-video-overlay">
<a class="tqm-play-btn">
</a>
</div>
<!-- WISTIA IN PLACE VIDEO EMBED CODE -->
<script src="https://fast.wistia.com/embed/medias/j04n260140.jsonp" async></script>
<script src="https://fast.wistia.com/assets/external/E-v1.js" async></script>
<div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;">
<div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;">
<div class="wistia_embed wistia_async_j04n260140 videoFoam=true" style="height:100%;width:100%"> </div>
</div>
</div>
<!-- END WISTIA IN PLACE VIDEO EMBED CODE -->
</div>
Below is the script:
window._wq = window._wq || [];
_wq.push({ id: "_all", onReady: function(wistiaEmbed) {
var wistiaHash = $(".wistia_embed").attr("id", "wistiaGenID_" + wistiaEmbed.hashedId());
var wistiaHashId = wistiaEmbed.hashedId();
// grab Wista API
wistiaEmbed = Wistia.api(wistiaHashId);
// when the video is stopped
wistiaEmbed.bind("end", function() {
$(this).find('.tqm-video-overlay').fadeIn("slow");
});
//when the video is paused
wistiaEmbed.bind("pause", function() {
$('.tqm-video-wrapper').find('.tqm-video-overlay').fadeIn("slow");
});
//when the video time changes
wistiaEmbed.bind("secondchange", function() {
$(this).find('.tqm-video-overlay').fadeOut("slow");
});
// when you click the custom play button
$('.tqm-video-overlay').click(function() {
if ($(this).parent().has(".wistia_embed")) {
wistiaEmbed.play();
$(this).fadeOut("slow");
}
});
}
});
Here is a link to a jsfiddle: https://jsfiddle.net/eilawen/bggu5s1q/7/
Is someone able to point me in the right direction? Thanks in advance.
Replace <VIDEO_ID> with your wistia Video ID
This will works
<script src="//fast.wistia.com/assets/external/E-v1.js" async></script>
<div class="wistia_embed wistia_async_<VIDEO_ID>" style="width:640px;height:360px;"></div>
<button id="play">Play</button>
<button id="pause">Pause</button>
<script>
window._wq = window._wq || [];
_wq.push({
id: "<VIDEO_ID>", onReady: function (video) {
console.log("I got a handle to the video!", video);
}
});
$("#play").click(function () {
_wq.push({
id: "<VIDEO_ID>", onReady: function (video) {
video.play();
}
});
})
$("#pause").click(function () {
_wq.push({
id: "<VIDEO_ID>", onReady: function (video) {
video.pause();
}
});
})
</script>
I'm new to JQuery and JavaScript and I have this situation:
<button style="background-color: #dfe52d;border:4px solid #dfe52d"
class="button" type="button" >Play Me!</button>
<audio class="audio" src="audio.mp3" type="audio/mpeg"></audio>
There are many buttons on my page, all with the same structure. For each button I want play a different sound:
$(document).ready(function(){
$("button").click(function(){
var isPlaying=false
var audio = $(this).next().attr("src");
var music = new Audio(audio);
if(isPlaying) {music.pause()}
else{music.play();$(this).text("Stop Me")}
});
});
When a button is clicked, the sound plays and the button text changes to "stop me". How can I write the code to stop the audio? Also, if the user presses another button the current song must stop. How can I achieve this? Thanks.
Try setting the isPlaying outside of the button click event and querying that so you know the state when you press the button. At the moment you set isPlaying to false every time you click.
var isPlaying=false
$(document).ready(function(){
$("button").on("click", function(){
var audio = $(this).next().attr("src");
var music = new Audio(audio);
if (!isPlaying) {
// Not playing, let's play
isPlaying = true;
music.play();
$(this).text("Stop Me")
} else {
// Stop the music
isPlaying = true;
music.pause();
$(this).text("Play");
};
});
});
Here's the cleanest solution. Most of the functionality you're looking for is already built into the JavaScript for audio tags.
<script>
$(document).ready(function(){
$("button").click(function(){
var audio = $(".audio")[0];
if (audio.paused) {
audio.play();
$(this).html("Stop me!");
} else {
audio.pause();
$(this).html("Play me!");
}
});
});
</script>
hi thanks all of you for the quick response.
unfortunately this two solution didnt work out, so i opted for this:
<button style="background-color: #dfe52d;border:4px solid #dfe52d;" class="button" onclick="document.getElementById('audio1').play()" type="button" >Play Me!</button>
<button style="background-color: #dfe52d;border:4px solid #dfe52d;" class="button" onclick="document.getElementById('audio1').pause()" type="button" >Stop Me!</button>
<button style="background-color: #dfe52d;border:4px solid #dfe52d;" class="button" onclick="document.getElementById('audio1').currentTime=0.0" type="button" >Restart Me!</button>
<audio class="audio" id="audio1" src="audio.mp3" type="audio/mpeg"></audio>
Now works fine except one problem, i need a function to stop the current sound when another button is pressed. Is it a simple task in your opinion? Thank you