i tried to built my website with audio player inside. But i have problem when i combined song that load from database with play button. I want to make my play button change when it clicked and load song from database. I have codes like these :
HTML and PHP
<div id="playbtn">
<button id="play_btn" onclick="playPause()"></button>
<?php
$song= "SELECT mp3Lagu FROM folksong WHERE songtitle = 'Apuse'";
$result = mysql_query($song);
while ($row = mysql_fetch_array($result)) {
echo'
<audio id="listenlagu">
<source src="data:audio/mp3;base64,'.base64_encode( $row['mp3Lagu'] ).'">
</audio>';
}
?></div>
I used javascript to change the display button like these :
JAVASCRIPT
<script>
var audio, playbtn;
function initAudioPlayer(){
audio = new Audio();
//audio = document.getElementById('listenlagu');
//audio.src = "audio/Apuse.mp3";
audio.src = document.getElementById('listenlagu');
audio.load();
audio.loop = true;
audio.play();
// Set object references
playbtn = document.getElementById("play_btn");
// Add Event Handling
playbtn.addEventListener("click",playPause);
// Functions
function playPause(){
if(audio.paused){
audio.play();
playbtn.style.background = "url(images/pause70.png) no-repeat";
} else {
audio.pause();
playbtn.style.background = "url(images/play70.png) no-repeat";
}
}
}
window.addEventListener("load", initAudioPlayer);
</script>
but it's not working when i combined with javascript -_____-"
Anyone know where the problems are ?
Can you help me to fix these ?
You should update the following (full code example below):
assign the src attribute to audio.src
move your playPause function outside of the initAudioPlayer function
make your playPause function accept 2 parameters 1 - "audio" (the new Audio object) and 2 - playbtn (the button element), and have it return a function so that it can be used as a callback in the addEventListenter method
Here is a working plunkr: https://plnkr.co/edit/bticzS?p=preview
initAudioPlayer();
function initAudioPlayer(){
var audio = new Audio();
var aContainer = document.getElementById('listenlagu');
// assign the audio src
audio.src = aContainer.querySelectorAll('source')[0].getAttribute('src');
audio.load();
audio.loop = true;
audio.play();
// Set object references
var playbtn = document.getElementById("play_btn");
// Add Event Handling
playbtn.addEventListener("click", playPause(audio, playbtn));
}
// Functions
function playPause(audio, playbtn){
return function () {
if(audio.paused){
audio.play();
playbtn.style.background = "url(images/pause70.png) no-repeat";
} else {
audio.pause();
playbtn.style.background = "url(images/play70.png) no-repeat";
}
}
}
Related
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.
So I have code that looks like this. I press the button and an mp3 plays. But I can't seem to find a way to make a stop button for this and was hoping y'all could help me.
Name of Song 1
Name of Song 2
var audios =
Array.prototype.map.call(document.getElementsByClassName("buttons")
, function (el) {
var audio = new Audio();
var src = el.id + ".mp3";
el.onclick = function () {
audio.src = src;
audio.play();
};
return audio;
});
I tried
function stopmusic() {
audio.pause();
}
document.getElementById('stopbuttons').addEventListener('click', stopmusic);
and
function stopmusic() {
audios.forEach(audio=>audio.pause());
audios.forEach(audio=>audio.currentTime = 0.0);
audios.forEach(audio=>audio.src = "");
}
document.getElementById('stopbutton').addEventListener('click', stopmusic);
but couldnt get it to work
use audio.pause(); to stop the audio
So I have these buttons that when pressed play a sound, and I wanted to make a button that when pressed would allow these sounds to loop. I dont know how to explain this correctly, so ill just show the code
function aud1play() {
aud1.src = "aud1.mp3";
aud1.play();
}
document.getElementById('aud1button').addEventListener('click', aud1play);
function aud2play() {
aud2.src = "aud2.mp3";
aud2.play();
}
document.getElementById('aud2button').addEventListener('click', aud2play);
function aud3play() {
aud3.src = "aud3.mp3";
aud3.play();
}
document.getElementById('aud3button').addEventListener('click', aud3play);
is there a way to take the names (aud1, aud2, aud3) and put (name).loop; under each of the functions with a button press without having to actually write the (name).loop; for every one?
Try this
JS:
function play(){
var audio = document.getElementById("audio");
audio.play();
}
HTML5:
<audio controls loop id="audio">
<source src="horse.mp3" type="audio/mpeg">
</audio>
You should look at the bind method: https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/
function playAudio(type) {
aud.src = (type === '1') ?
"aud1.mp3" :
(type === "2") ?
"aud2.mp3" :
"aud3.mp3";
aud.play();
}
document.getElementById('aud1button').addEventListener('click', playAudio.bind("1"));
document.getElementById('aud2button').addEventListener('click', playAudio.bind("2"));
document.getElementById('aud3button').addEventListener('click', playAudio.bind("3"));
You could do something like this:
// create an object containing all audio objects
var audios = (function () {
var names = ['aud1.mp3', 'aud2.mp3', 'aud3.mp3'];
var audios = {};
for (var index in names) {
var audio = audios[names[index]] = new Audio();
audio.src = names[index];
}
return audios;
})();
function toggleAudioPlay () {
// "this" refers to the button that was clicked
var name = this.getAttribute('data-audio-src'); // read the button's "data-audio-src" attribute
if (!audios.hasOwnProperty(name)) {
// audio doesn't exist
return;
}
var audio = audios[name];
audio.src = name;
// toggle the play state
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
}
function toggleAudioLoop () {
var name = this.getAttribute('data-audio-src');
if (!audios.hasOwnProperty(name)) {
// audio doesn't exist
return;
}
var audio = audios[name];
audio.loop = !audio.loop;
}
document.querySelector('.audio-button-toggle-play').forEach(function (button) {
button.addEventListener('click', toggleAudioPlay);
});
document.querySelector('.audio-button-toggle-loop').forEach(function (button) {
button.addEventListener('click', toggleAudioLoop);
});
Now, you could have the following HTML:
<button class="audio-button-toggle-play" data-audio-src="aud1.mp3">Play/Pause the first audio</button>
<button class="audio-button-toggle-play" data-audio-src="aud2.mp3">Play/Pause the second audio</button>
<button class="audio-button-toggle-play" data-audio-src="aud3.mp3">Play/Pause the third audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud1.mp3">Enable/Disable looping of the first audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud2.mp3">Enable/Disable looping of the second audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud3.mp3">Enable/Disable looping of the third audio</button>
That way, you don't have to create a new function for each audio. Just add a new audio file to the "names" array and add a button with a special class (audio-button-toggle-play in order to toggle the play state of an audio) and a data-audio-src attribute containing the location of the audio file.
I have the following html and script to play/pause an audio by clicking a button.
<audio id="testAudio" hidden src="sample.mp3" type="audio/mpeg">
</audio>
<button id="playAudio">Play</button>
<script>
document.getElementById("playAudio").addEventListener("click", function(){
var audio = document.getElementById('testAudio');
if(this.className == 'is-playing'){
this.className = "";
this.innerHTML = "Play"
audio.pause();
}else{
this.className = "is-playing";
this.innerHTML = "Pause";
audio.play();
}
});
</script>
I need to edit it in such a way as to play multiple mp3 files one by one in a defined order and stop only when the last audio has played.
I just don't know how to make that work. Can anyone help?
You can register an event handler for the audio tag, that first when the current file has finished;
document.getElementById("testAudio").addEventListener("ended",function(e) {
// Play next track
});
If you have a list of tracks to play in an array, then simply play the next one after the current track has finished. Using the setTimeout function you can put in a delay between the tracks. A simple example is as follows;
<script>
var playlist= [
'https://api.twilio.com/cowbell.mp3',
'https://demo.twilio.com/hellomonkey/monkey.mp3'
];
var currentTrackIndex = 0;
var delayBetweenTracks = 2000;
document.getElementById("playAudio").addEventListener("click", function(){
var audio = document.getElementById('testAudio');
if(this.className == 'is-playing'){
this.className = "";
this.innerHTML = "Play"
audio.pause();
}else{
this.className = "is-playing";
this.innerHTML = "Pause";
audio.play();
}
});
document.getElementById("testAudio").addEventListener("ended",function(e) {
var audio = document.getElementById('testAudio');
setTimeout(function() {
currentTrackIndex++;
if (currentTrackIndex < playlist.length) {
audio.src = playlist[currentTrackIndex];
audio.play();
}
}, delayBetweenTracks);
});
</script>
Note that cowbell track is 52 seconds long, so if your testing the above (for your own sanity) set the controls property to the audio tag so you can skip through most of it.
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);
});