I have the following code in javascript that plays a sound
function muzplay() {
var muz = document.getElementById("song");
var button = document.getElementById("play");
if (muz.paused) {
muz.play();
button.textContent = "||";
} else {
muz.pause();
button.textContent = ">";
}
}
but it doesn't starts when the page is loading for the first time.
How can I make the song start when the page is loading?
If I would like to add an image as a button, instead of "button.textContent = "||";" what command can I use. for example I want to use a customize play and pause button instead of the || and > text.
window.onload = function(){ muzplay();}
// or
window.document.onload = function(){ muzplay();}
// or
muzplay();
Related
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".
This is how my script looks like:
<script>
var obj = document.createElement("audio");
document.body.appendChild(obj);
obj.src = "http://example.com/audios/Kalimba.mp3";
obj.load();
obj.volume = 0.3;
obj.preLoad = true;
obj.controls = true;
$(".testspeech").click(function() {
obj.paused?obj.play():obj.pause()
});
</script>
Then in the HTML I have a button that is meant to play and/or pause the video.
However, when I load the page nothing happens when I click on the play button.
Anything I could have possibly done wrong here?
Here is the HTML:
<button class="testspeech">
play/pause
</button>
As far as I can tell the reason your sound isn't playing is that the src for the actual sound is not valid. I've created a JSFiddle (here) to test it out, and after replacing the sound clip link it works as expected.
$(document).ready(function() {
var obj = document.createElement("audio");
document.body.appendChild(obj);
obj.src = "https://www.kozco.com/tech/piano2.wav";
obj.load();
obj.volume = 0.3;
obj.preLoad = true;
obj.controls = true;
$(".testspeech").on('click', function() {
obj.paused ? obj.play() : obj.pause()
});
});
I'm using code that plays sound whn image is loaded (i'm using this as a play button on music player). But I have a problem, you can't stop sound when image is clicked (play button). So, do you know how can I make on this code, so sound pause when image is clicked.
My code:
<script type="text/javascript">
//Create new function that will update the image source on click.
function updateImage(el, soundfile) {
//Determine if music is playing or paused then adjust image
source accordingly.
if(soundfile.mp3.paused) {
el.src =
"imageurl.com";
} else {
el.src = "secondimageurl.com";
}
};
function playSound(el,soundfile) {
if (el.mp3) {
if(el.mp3.paused) el.mp3.play();
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
//Call new function made whenever the sound is toggled.
updateImage(document.getElementById("Bottom-1"), el);
};
</script>
<body onload="playSound(this, 'soundsource.mp3');">
<img src="buttonimage.html" name="Bottom-1" width="50" height="45"
border="0" id="Bottom-1"/>
</span>
</body>
Use SoundPlayer.js.
// Initialize
const player = new SoundPlayer();
// Load the sound
const sound = player.load('Sound.mp3');
// Play the sound
sound.play();
// load & play in one line
const sound = player.load('Sound.mp3').play();
And bind the image onclick event
image.onclick = function () {
sound[ sound.isPlaying ? 'pause' : 'play' ]();
image.src = sound.isPlaying ? 'isPlaying.jpg' : 'isPaused.jpg';
}
Full fiddle: https://jsfiddle.net/GustavGenberg/dxgph924/
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.
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.