Javascript to stop playing sound when another starts - javascript

So, I'm a complete amateur when it comes to coding, but I still like to fiddle around with it.
I'm currently working on a html/jS/PHP based soundboard and I can't figure out how to stop sound from playing when pressing a button to play another one.
<script type="text/javascript" charset="utf-8">
$(function() {
$("audio").removeAttr("controls").each(function(i, audioElement) {
var audio = $(this);
var that = this; //closure to keep reference to current audio tag
$("#doc").append($('<button>'+audio.attr("title")+'</button>').click(function() {
that.play();
}));
});
});
</script>
I hope someone understands that. Thanks in advance.
There is also a PHP code to fetch the audio file automatically from the folder to the front end, probably unnecessary info for this problem.

This is not very difficult to do if you use HTML5 which introduced the HTMLAudioElement.
Here is the minimal code for what you are trying to do:
// Let's create a soundboard module ("sb")
var sb = {
song: null,
init: function () {
sb.song = new Audio();
sb.listeners();
},
listeners: function () {
$("button").click(sb.play);
},
play: function (e) {
sb.song.src = e.target.value;
sb.song.play();
}
};
$(document).ready(sb.init);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Audio</title>
</head>
<body>
<button value="https://www.gnu.org/music/FreeSWSong.ogg">Song #1</button>
<button value="https://www.gnu.org/music/free-software-song-herzog.ogg">Song #2</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
You may also consider libraries like howler.js to help you in the development process.

What you could do, is before start playing a new audio pause all available audio on the page. Something like this.
var audioOne = document.querySelector('#audio-1');
var audioTwo = document.querySelector('#audio-2');
var allAudios = document.querySelectorAll('audio');
function stopAllAudio(){
allAudios.forEach(function(audio){
audio.pause();
});
}
document.querySelector('#play-1').addEventListener('click', function(){
stopAllAudio();
audioOne.play();
})
document.querySelector('#play-2').addEventListener('click', function(){
stopAllAudio();
audioTwo.play();
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<audio id="audio-1"
src="http://developer.mozilla.org/#api/deki/files/2926/=AudioTest_(1).ogg">
</audio>
<audio id="audio-2"
src="http://www.w3schools.com/html/horse.mp3">
</audio>
<button id="play-1">
play audio 1
</button>
<button id="play-2">
play audio 2
</button>
</body>
</html>
Instead of adding audio using <audio> tag you could use HTMLAudioElement.

You can stop and reset an audio element by pausing it and setting its current time to 0. You would need to do this whenever a button is clicked. Example:
// Available sounds:
const sounds = {
"Bottle": "http://freewavesamples.com/files/Bottle.wav",
"Bamboo": "http://freewavesamples.com/files/Bamboo.wav"
}
// Load audio elements:
let audios = {};
for (let [title, url] of Object.entries(sounds)) {
audios[title] = new Audio(url);
}
// Create board buttons:
let board = document.getElementById("board");
for (let title of Object.keys(audios)) {
let button = document.createElement("button");
button.textContent = title;
button.dataset["audio"] = title;
board.appendChild(button);
}
// Handle board button clicks:
board.addEventListener("click", function(event) {
let audio = audios[event.target.dataset["audio"]];
if (audio) {
// Pause and reset all audio elements:
for (let audio of Object.values(audios)) {
audio.pause();
audio.currentTime = 0;
}
// Play this audio element:
audio.play();
}
});
<div id="board"></div>
In case you want to leverage the full power of the Web Audio API, you would probably start building your soundboard similar to this:
// Load buffer from 'url' calling 'cb' on complete:
function loadBuffer(url, cb) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.responseType = 'arraybuffer';
request.onload = () => context.decodeAudioData(request.response, cb);
request.send();
}
// Available sounds:
const sounds = {
"Bottle": "url/to/bottle.wav",
"Bamboo": "url/to/bamboo.wav"
};
let audioCtx = new (AudioContext || webkitAudioContext)(),
board = document.getElementById("soundboard"),
buffers = {},
source;
// Load buffers:
for (let [title, url] of Object.entries(sounds)) {
loadBuffer(url, buffer => buffers[title] = buffer);
}
// Create board buttons:
for (let title of Object.keys(sounds)) {
let button = document.createElement("button");
button.textContent = title;
button.dataset["buffer"] = title;
board.appendChild(button);
}
// Handle board button clicks:
board.addEventListener("click", function(event) {
let buffer = buffers[event.target.dataset["buffer"]];
if (buffer) {
if (source) source.stop();
source = audioCtx.createBufferSource();
source.buffer = buffer;
source.connect(audioCtx.destination);
source.start();
}
});
<div id="soundboard"></div>
Please note that the sound URLs given above must either be on the same domain or available under the same origin policy (see CORS headers).

Below code may help others:
var audioMap = new Map();
var rappers = document.querySelectorAll('.rapper');
rappers.forEach(function(rapper){
audioMap.set(rapper, new Audio());
rapper.addEventListener('click', function(){
var audio = new Audio($(this).data('audio'));
audio.play();
audioMap.set(this, audio);
var current = audioMap.get(this);
// console.log('get', current);
audioMap.forEach(function(audio){
if( audio != current ){
audio.pause();
audio.currentTime = 0;
}
});
});
});

For the ones that don't use the audioTag in HTML5 and want to use only vanilla js this may help ya
var songplaying = null; //This is where we will store the current playing song
function playsong(song_name){
//settings
var playing = null;
if(songplaying==null){ //If a song isn't stored that means that it's not playing and vice versa
playing = false;
}else{
playing = true;
}
var dir = "./songs/"+song_name+".mp3"; //Here we get the directory of the song
var song = new Audio(dir); //Making a new audio element
if(!playing){ //This runs when no song is playing
song.play();
songplaying=song; //We save the current playing song
}else{ //This runs when another song is already playing
var song_alredyplaying = songplaying; //We get the audio element (song)
song_alredyplaying.pause(); //Pause the song
song.play(); //Then we play the new song
songplaying=song; //Save the current playing song
}
}
//Example
var playbtn = document.querySelector(".play");
playbtn.addEventListener('click', function(){
playsong("the song name");
};

Related

Record Audio and Save it to specific drive in computer in ASP.NET

I have attached a sample code.Just I need to know how can I save the audio file to my drive Ex- D://RecordedAudios//.
I attached the whole code which I have done.
What I want to achieve is when I click on STOP it will save my audio to the given drive because I wanted to create a form where user record the audio and the click on stop it save to my project or specific drive so later I use to get it back.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AudioRecord2.aspx.cs" Inherits="Extra_AudioRecord2" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Recorder.js demo with record, stop and pause</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Simple Recorder.js demo</h1>
<p>
Matt Diamond‘s Recorder.js is a popular JavaScript library for recording audio in the browser as uncompressed pcm audio in .wav containers. Before it the only way to record audio was to use Flash.
</p>
<p>Check out the code on GitHub and our blog post on using Recorder.js to capture WAV audio.</p>
<div id="controls">
<button id="recordButton">Record</button>
<button id="pauseButton" disabled>Pause</button>
<button id="stopButton" disabled>Stop</button>
</div>
<div id="formats">Format: start recording to see sample rate</div>
<h3>Recordings</h3>
<ol id="recordingsList"></ol>
<!-- inserting these scripts at the end to be able to use all the elements in the DOM -->
<script src="https://cdn.rawgit.com/mattdiamond/Recorderjs/08e7abd9/dist/recorder.js"></script>
<script>
URL = window.URL || window.webkitURL;
var gumStream; //stream from getUserMedia()
var rec; //Recorder.js object
var input; //MediaStreamAudioSourceNode we'll be recording
// shim for AudioContext when it's not avb.
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext //audio context to help us record
var recordButton = document.getElementById("recordButton");
var stopButton = document.getElementById("stopButton");
var pauseButton = document.getElementById("pauseButton");
//add events to those 2 buttons
recordButton.addEventListener("click", startRecording);
stopButton.addEventListener("click", stopRecording);
pauseButton.addEventListener("click", pauseRecording);
function startRecording() {
console.log("recordButton clicked");
/*
Simple constraints object, for more advanced audio features see
https://addpipe.com/blog/audio-constraints-getusermedia/
*/
var constraints = { audio: true, video: false }
/*
Disable the record button until we get a success or fail from getUserMedia()
*/
recordButton.disabled = true;
stopButton.disabled = false;
pauseButton.disabled = false
/*
We're using the standard promise based getUserMedia()
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
*/
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
console.log("getUserMedia() success, stream created, initializing Recorder.js ...");
/*
create an audio context after getUserMedia is called
sampleRate might change after getUserMedia is called, like it does on macOS when recording through AirPods
the sampleRate defaults to the one set in your OS for your playback device
*/
audioContext = new AudioContext();
//update the format
document.getElementById("formats").innerHTML = "Format: 1 channel pcm # " + audioContext.sampleRate / 1000 + "kHz"
/* assign to gumStream for later use */
gumStream = stream;
/* use the stream */
input = audioContext.createMediaStreamSource(stream);
/*
Create the Recorder object and configure to record mono sound (1 channel)
Recording 2 channels will double the file size
*/
rec = new Recorder(input, { numChannels: 1 })
//start the recording process
rec.record()
console.log("Recording started");
}).catch(function (err) {
//enable the record button if getUserMedia() fails
recordButton.disabled = false;
stopButton.disabled = true;
pauseButton.disabled = true
});
}
function pauseRecording() {
console.log("pauseButton clicked rec.recording=", rec.recording);
if (rec.recording) {
//pause
rec.stop();
pauseButton.innerHTML = "Resume";
} else {
//resume
rec.record()
pauseButton.innerHTML = "Pause";
}
}
function stopRecording() {
console.log("stopButton clicked");
//disable the stop button, enable the record too allow for new recordings
stopButton.disabled = true;
recordButton.disabled = false;
pauseButton.disabled = true;
//reset button just in case the recording is stopped while paused
pauseButton.innerHTML = "Pause";
//tell the recorder to stop the recording
rec.stop();
//stop microphone access
gumStream.getAudioTracks()[0].stop();
//create the wav blob and pass it on to createDownloadLink
rec.exportWAV(createDownloadLink);
}
function createDownloadLink(blob) {
var url = URL.createObjectURL(blob);
var au = document.createElement('audio');
var li = document.createElement('li');
var link = document.createElement('a');
//name of .wav file to use during upload and download (without extendion)
var filename = new Date().toISOString();
//add controls to the <audio> element
au.controls = true;
au.src = url;
//save to disk link
link.href = url;
link.download = filename + ".wav"; //download forces the browser to donwload the file using the filename
link.innerHTML = "Save to disk";
//add the new audio element to li
li.appendChild(au);
//add the filename to the li
li.appendChild(document.createTextNode(filename + ".wav "))
//add the save to disk link to li
li.appendChild(link);
//upload link
var upload = document.createElement('a');
upload.href = "#";
upload.innerHTML = "Upload";
upload.addEventListener("click", function (event) {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", blob, filename);
xhr.open("POST", "upload.php", true);
xhr.send(fd);
})
li.appendChild(document.createTextNode(" "))//add a space in between
li.appendChild(upload)//add the upload link to li
//add the li element to the ol
recordingsList.appendChild(li);
}
</script>
</body>
</html>
As per my understanding, If you are trying to save on Server then you can save on desired drive/location but at the client side, you will not have that access for security reasons, you will need to pass data to the browser and browser will save to clients PC/device, you can set location in browser settings for specific location

javascript record voice stop and save it on the 20 second

I took and modified code which record our voice and after click of stop button make it like .wav file. I made the code to start record onload and set function which click automatically after 20sec the stop button. But these function doesn't work! This code is right after function startRecording() {
console.log("recordButton clicked");. The code which doesn't work is setTimeout("function() {document.getElementById('stopRecording').click();}", 5000);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Recorder.js demo with record, stop and pause</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body onload='startRecording()'>
<div id="controls">
<button id="recordButton" >Record</button>
<button id="pauseButton" disabled>Pause</button>
<button id="stopButton" disabled>Stop</button>
</div>
<h3>Recordings</h3>
<ol id="recordingsList"></ol>
<!-- inserting these scripts at the end to be able to use all the elements in the DOM -->
<script src="https://cdn.rawgit.com/mattdiamond/Recorderjs/08e7abd9/dist/recorder.js"></script>
<script>
URL = window.URL || window.webkitURL;
var gumStream; //stream from getUserMedia()
var rec; //Recorder.js object
var input; //MediaStreamAudioSourceNode we'll be recording
// shim for AudioContext when it's not avb.
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext; //new audio context to help us record
var recordButton = document.getElementById("recordButton");
var stopButton = document.getElementById("stopButton");
var pauseButton = document.getElementById("pauseButton");
//add events to those 3 buttons
recordButton.addEventListener("click", startRecording);
stopButton.addEventListener("click", stopRecording);
pauseButton.addEventListener("click", pauseRecording);
function startRecording() {
console.log("recordButton clicked");
setTimeout("function() {document.getElementById('stopRecording').click();}", 5000);
/*
Simple constraints object, for more advanced audio features see
<div class="video-container"><blockquote class="wp-embedded-content" data-secret="vNsz0nPBL4">Supported Audio Constraints in getUserMedia()</blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted" style="position: absolute; clip: rect(1px, 1px, 1px, 1px);" src="https://addpipe.com/blog/audio-constraints-getusermedia/embed/#?secret=vNsz0nPBL4" data-secret="vNsz0nPBL4" width="600" height="338" title="“Supported Audio Constraints in getUserMedia()” — Pipe Blog" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></div>
*/
var constraints = { audio: true, video:false }
/*
Disable the record button until we get a success or fail from getUserMedia()
*/
recordButton.disabled = true;
stopButton.disabled = false;
pauseButton.disabled = false
/*
We're using the standard promise based getUserMedia()
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
*/
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
console.log("getUserMedia() success, stream created, initializing Recorder.js ...");
/* assign to gumStream for later use */
gumStream = stream;
/* use the stream */
input = audioContext.createMediaStreamSource(stream);
/*
Create the Recorder object and configure to record mono sound (1 channel)
Recording 2 channels will double the file size
*/
rec = new Recorder(input,{numChannels:1})
//start the recording process
rec.record()
console.log("Recording started");
}).catch(function(err) {
//enable the record button if getUserMedia() fails
recordButton.disabled = false;
stopButton.disabled = true;
pauseButton.disabled = true
});
}
function pauseRecording(){
console.log("pauseButton clicked rec.recording=",rec.recording );
if (rec.recording){
//pause
rec.stop();
pauseButton.innerHTML="Resume";
}else{
//resume
rec.record()
pauseButton.innerHTML="Pause";
}
}
function stopRecording() {
console.log("stopButton clicked");
//disable the stop button, enable the record too allow for new recordings
stopButton.disabled = true;
recordButton.disabled = false;
pauseButton.disabled = true;
//reset button just in case the recording is stopped while paused
pauseButton.innerHTML="Pause";
//tell the recorder to stop the recording
rec.stop();
//stop microphone access
gumStream.getAudioTracks()[0].stop();
//create the wav blob and pass it on to createDownloadLink
rec.exportWAV(createDownloadLink);
}
function createDownloadLink(blob) {
var url = URL.createObjectURL(blob);
var au = document.createElement('audio');
var li = document.createElement('li');
var link = document.createElement('a');
//add controls to the <audio> element
au.controls = true;
au.src = url;
//link the a element to the blob
link.href = url;
link.download = new Date().toISOString() + '.wav';
link.innerHTML = link.download;
//add the new audio and a elements to the li element
li.appendChild(au);
li.appendChild(link);
//add the li element to the ordered list
recordingsList.appendChild(li);
}
</script>
</body>
</html>
It is possible to record audio with a vanilla JavaScript.
For example
<button id="audioRecordButton">RECORD</button>
function recordAudioFromMicrophone()
{
var mediaRecorder;
var audioRecordButton = document.getElementById( "audioRecordButton" );
var time;
var isStartRec = true;
var run = function(stream)
{
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.addEventListener("dataavailable", getAudio);
audioRecordButton.addEventListener("click", recordHandler);
}
function recordHandler()
{
if(isStartRec)
{
startRec();
time = setTimeout(stopRec, 20000);
}
else
{
stopRec();
clearTimeout(time);
}
}
function startRec()
{
mediaRecorder.start();
isStartRec = false;
}
function stopRec()
{
mediaRecorder.stop();
isStartRec = true;
}
function getAudio(blob){...}
const enableAudio = { audio: true };
navigator.mediaDevices.getUserMedia(enableAudio).then(run);
}

Cannot get audio to play in JavaScript soundboard (total newbie here)

I'm trying to create, as a starting excercise, a soundboard for our D&D sessions. I'm currently trying to make it so that when a button is clicked, the variable 'audio' is set to that, and that it then runs the function to play or pause audio, depending on whether it's running or not. I have JS and HTML in the same file (I realise this isn't good, however). Below is my code:
<button id="play1st">Heroic Battle Music</button>
<button id="play2nd">Military Battle Music</button>
<button id="play3rd">Stronghold Battle Music</button>
<!--Audio to be played -->
<audio id="heroic" src="heroic.mp3"></audio>
<audio id="combat_rome" src="combat_rome.mp3"></audio>
<audio id="stronghold" src="stronghold.mp3"></audio>
<!--JavaScript audio -->
<script>
function playMusic() {
document.getElementById("play1st").addEventListener ('click', music1());
document.getElementById("play2nd").addEventListener ('click', music2());
document.getElementById("play3rd").addEventListener ('click', music3());
var isPlaying = false;
function music1() {
var audio = new Audio("heroic.mp3");
togglePlay();
};
function music2() {
var audio = new Audio("combat_rome.mp3");
togglePlay();
};
function music3() {
var audio = new Audio("stronghold.mp3");
togglePlay();
};
function togglePlay(){
if (isPlaying){
pause()
} else {
audio.play();
}
};
audio.onplaying = function () {
isPlaying = true;
};
audio.onpause = function () {
isPlaying = false;
}};
</script>
I'm probably missing something very basic, so any explanation would be most welcome. Thank you!

how to play the audio using javascript (by input)

function playSound(buffer) {
aSoundSource = audioContext.createBufferSource(); source.
aSoundSource.buffer = buffer;
aSoundSource.connect(gainNode);
gainNode.connect(analyser);
var volX = volControl();
//gainNode.gain.value = 0.1;
gainNode.gain.value = volX;
analyser.connect(audioContext.destination);
aSoundSource.start(0);
document.title = document.getElementById("files").value;
playing = true;
requestAnimFrame(drawVisualisation);
}
///////////////////////////////////////
function play(){
var audio = new Audio('test.mp3');
audio.play();
}
second function is working perfectly its i have called particular audio to play its working for button here i want to input a song and play
Havent tested but this is the rough idea
document.getElementById("inputFile").onchange = loadMusic
function loadMusic(e) {
console.log(e.target.value)
var audio = new Audio(e.target.value)
audio.play();
}
<input type="file" id="inputFile">

Processor Audio JavaScript HTML5

There is a js-script:
<script>
function start1() {
var audio = new Audio();
audio.src = URL.createObjectURL(document.getElementById('f1').files[0]);
audio.autoplay = true;
}
function start2() {
var audio = new Audio();
audio.src = URL.createObjectURL(document.getElementById('f2').files[0]);
audio.autoplay = true;
}
...
function stop() {
var audio = new Audio();
audio.stop();
}
</script>
and html code:
<body>
<input type="file" id="f1"></input>
<input type="file" id="f2"></input>
...
<button onmousedown="start1()" onmouseup="stop()">1</button>
<button onmousedown="start2()" onmouseup="stop()">2</button>
...
As can be understood through the script, he plays a sound file that loads by using the form files.
But there are two problems:
1) requires that sound is played only during events pressing (onmousedown) and stops when the mouse button is released (onmouseup).
Now the sound is played to the end it does not matter whether you clicked the mouse button and let go of it (because there is no test for this condition).
2) also need to create a simplified version of the script, as the functions for processing should be 16 pieces, but not manually register the same each function. You must create a generated script that will process the N-number of id (start1, start2, etc., f1, f2, etc).
Help to modify the code, you can also fully code jquery. It is not critical.
Thank you.
You can use local variables, you just need an identifier to find the audio element later. You also need to append the audio element to the DOM.
Also, you have to use pause() not stop().
<script>
function start(id, source) {
var aud = document.getElementById(id);
if (aud) {
aud.parentNode.removeChild(aud);
}
var audio = new Audio();
audio.setAttribute("id", id);
audio.src = URL.createObjectURL(document.getElementById(source).files[0]);
document.body.appendChild(audio);
audio.autoplay = true;
}
function stop(id) {
var aud = document.getElementById(id);
aud.pause();
}
</script>
<input type="file" id="f1"></input>
<input type="file" id="f2"></input>
<button onmousedown="start('1', 'f1')" onmouseup="stop('1')">1</button>
<button onmousedown="start('2', 'f2')" onmouseup="stop('2')">2</button>
This should work (Untested):
<script>
var a1 = new Audio();
var a2 = new Audio();
function start1() {
a1.src = URL.createObjectURL(document.getElementById('f1').files[0]);
a1.autoplay = true;
}
function start2() {
a2.src = URL.createObjectURL(document.getElementById('f2').files[0]);
a2.autoplay = true;
}
function stop() {
a1.stop();
a2.stop();
}
</script>

Categories

Resources