Request permission to automatically play an audio file - javascript

I have a function in js that checks a variable date, and if it is present it starts an audio file.
Since with the new privacy it is not possible to start an audio file automatically, in fact in my case it is blocked.
I would like to have the broswer box appear to give consent to the reproduction of the audio file.
But, I do not know how can I do it.
Can you help me?
var audio = new Audio('/sound/file-one.mp3');
setInterval(function() {
$.ajax({
url: '/check_data.php',
type: 'post',
data: {
'check_data' : 1
},
success: function(response){
if (response != "false") {
audio.addEventListener('ended', function () {
audio.play();
}, false);
audio.play();
}
}
});
}, 5000);

User must start Audio, after Audio is started by a user action, you can change source whenever you want.
const audio = document.getElementById("au");
let bt = document.getElementById("bt");
console.log(audio);
bt.addEventListener("click", ()=>{
audio.play();
});
const startPlaying = ()=>{
audio.removeEventListener('playing', startPlaying);
bt.classList.add("hide");
audio.src = 'https://freesound.org/data/previews/475/475736_4397472-lq.mp3';
audio.play();
}
audio.addEventListener('playing', startPlaying);
audio.addEventListener('error', ()=>{
console.log("error");
});
.hide{
display:none;
}
<input id="bt" type="button" value="Accept">
<audio id="au" preload="auto" src="https://raw.githubusercontent.com/anars/blank-audio/master/500-milliseconds-of-silence.mp3"></audio>

Related

Javascript: Microphone audio to download link?

I'm trying to record audio from the microphone and then add a download link for it.
This is my current code:
<!DOCTYPE html>
<html>
<head>
<title>Weird Problem</title>
<script>
function microphone() {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(function(stream) {
var recorder = new MediaRecorder(stream);
var chunks = [];
recorder.ondataavailable = function(e) {
chunks.push(e.data);
}
recorder.onstop = function() {
stream.getTracks()[0].stop();
var blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
var url = window.URL.createObjectURL(blob);
document.getElementById("player").src = url;
document.getElementById("upload").href = url;
document.getElementById("upload").download = "test.ogg";
}
recorder.start();
setTimeout(function() {
recorder.stop();
}, 5000);
}).catch(function(error) {
console.log(error);
});
}
}
</script>
</head>
<body>
<input type="button" value="Record Microphone" onclick="microphone();">
<br>
<audio controls id="player"></audio>
<br>
<a id="upload">Download Microphone Recording</a>
</body>
</html>
I'm on Chrome, and for me it plays the microphone audio correctly, but when I try to download it, the file won't play or even open.
I get various errors that the file contains data in an unknown format, so I think it's something to do with the audio headers.
Any help would be highly appreciated!
It turns out this issue is a bit more complicated than I expected.
I'm now adapting code from Recorder.js.
The online demo does exactly what I need.

Video stream to canvas to image using JavaScript for Project Oxford

I've been able to use Project Oxford, specifically the Emotions API by manually asking a user to upload pictures. However, I'm now looking to do this using a video stream (the webpage shows a live video stream from their webcam and the user can take a snapshot of the stream and then choose to have the emotions API run on that image, which will then run the API and show the scores in a dialogue window - this is the part which I am currently stuck with).
Below I've written the HTML and JavaScript code which sets up the video stream on the webpage and then allows the user to take a snapshot, which then converts the canvas to an image.
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<img id="file" src = "" alt="Emotions">
<!--input type="file" id="file" name="filename"-->
<button id="btn">Click here</button>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
var dataURL = document.getElementById("canvas");
if (dataURL.getContext){
var ctx = dataURL.getContext("2d");
var link = document.createElement('a');
link.download = "test.png";
var myImage = link.href = dataURL.toDataURL("image/png").replace("image/png", "image/octet-stream");
link.click();
}
var imageElement = document.getElementById("file");
imageElement.src = myImage;
//document.getElementById("file").src = dataURL;
$('#btn').click(function () {
//var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: imageElement,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
//alert(error.getAllResponseHeaders());
alert("Error");
});
});
});
}, false);
</script>
I'm not able to get the API running on the image after it's been converted as a canvas. After reading around, I believe this has something to do with the file extension that's given to the image after it's been converted as a canvas (there is none), as the API only allows for image file types. I believe this might be where the problem lies and any help would be very much appreciated. Many thanks!
This is the code I'm using to upload the picture to a backend API, which then use the .NET SDK after adding some business logic.
It is not the exact same scenario but the Javascript code might help you:
var url = 'Home/upload';
var data = new FormData();
data.append('file', imgData);
var imgData = canvas.msToBlob('image/jpeg');
$.ajax({
type: 'POST',
url: url,
data: data,
processData: false,
contentType: false
})
.done(function (response) {
loading.style.display = "none";
if (response.error != "") {
result.innerText = response.error;
}
else {
result.innerHTML = response.result;
}
})
.fail(function (response) {
alert('Error : ' + response.error);
})
.complete(function (response) {
restartButton.style.display = 'inline-block';
});
The following thread helped me: Pass Blob through ajax to generate a file

Chrome Extension tabCapture API Audio Stream to Play in HTML Page

I am creating a chrome extension which captures audio from a tab using the chrome tabCapture API. I would like to play this audio stream in another html page in hopes of eventually creating a visualizer for it.
I capture the audio in a background script like so
chrome.browserAction.onClicked.addListener(function(activeTab) {
var constraints = {
audio: true,
video: false,
};
var visualizerPage = chrome.extension.getURL("/views/visualizer.html");
chrome.tabCapture.capture(constraints, function(stream) {
console.log("\ngot stream");
console.log(stream);
chrome.tabs.create({
url: visualizerPage
}, function(tab) {
chrome.tabs.sendMessage(tabID, {
"message": "stream",
"stream": stream
});
});
});
the audio stream is captured from whatever page the extension was clicked on. Another tab is opened, and the audio stream is sent to it as a message.
The javascript for the visualizer.html page is
function loadStream(stream) {
// what do I have to put here to play the stream?
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.message === "stream") {
var stream = request.stream;
if (!stream) {
console.log("stream is null");
return;
}
console.log(stream);
loadStream(stream);
}
else if (request.message === "statusChanged") {
console.log("statusChanged");
}
});
What I have so far is to load the audio stream into the web audio api using an audio context
var context = new AudioContext();
var source = context.createMediaStreamSource(stream);
but the script just hangs when trying to create the source.
The problem is I am not really sure what type the stream is (tabCapture api says its a LocalMediaStream).
How can I get the page to play the audio stream?
Try this in loadStream function:
var audio = new Audio();
audio.src = URL.createObjectURL(stream);
audio.play();

Play audio and restart it onclick

I'm looking to restart an audio file in a HTML5 audio player. I have defined a audio file and a play button.
<audio id="audio1" src="01.wav"></audio>
<button onClick="play()">Play</button>
When I click the play button the audio file starts playing, but when I click the button again the audio file doesn't stop and will not play again until it reaches the end of the file.
function play() {
document.getElementById('audio1').play();
}
Is there a method that would allow me to restart the audio file when I click the button using onclick rather than waiting for the song to stop?
To just restart the song, you'd do:
function play() {
var audio = document.getElementById('audio1');
if (audio.paused) {
audio.play();
}else{
audio.currentTime = 0
}
}
FIDDLE
To toggle it, as in the audio stops when clicking again, and when click another time it restarts from the beginning, you'd do something more like :
function play() {
var audio = document.getElementById('audio1');
if (audio.paused) {
audio.play();
}else{
audio.pause();
audio.currentTime = 0
}
}
FIDDLE
soundManager.setup({
preferFlash: false,
//, url: "swf/"
onready: function () {
soundManager.createSound({
url: [
"http://www.html5rocks.com/en/tutorials/audio/quick/test.mp3", "http://www.html5rocks.com/en/tutorials/audio/quick/test.ogg"
],
id: "music"
});
soundManager.createSound({
url: [
"http://www.w3schools.com/html/horse.mp3",
],
id: "horse"
});
soundManager.play("music");
}
}).beginDelayedInit();
And to start horse and pause all other sounds currently playing in a click event:
$("#horse").click(function () {
soundManager.stopAll();
soundManager.play("horse");
});
function sound(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
//this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function () {
this.sound.play();
}
this.stop = function () {
this.sound.pause();
this.sound.currentTime = 0
}
}
you can use the /above function to play sound
let mysound1 = new sound('xyz.mp3')
mysound1.play()

How to pause streaming in soundcloud javascript api

I would like to allow a sound file to play and pause. The documentation shows how to play a streaming file:
$("#stream").live("click", function(){
SC.stream("/tracks/{'track-id'}", function(sound){
sound.play();
};
It uses Sound Manager to stream and uses some of it's objects and methods... like .pause()!
So here's the code i think should work:
var is_playing="false";
$("#stream").live("click", function(){
SC.stream("/tracks/{'track-id'}", function(sound){
if (is_playing==="true")
{
sound.pause();
is_playing = "false";
console.log(is_playing);
}
else if (is_playing === "false")
{
sound.play();
is_playing = "true";
console.log(is_playing);
}
});
However, it continues to play the track without pausing. Any ideas?
Thanks.
var is_playing = false;
soundManager.setup({
url: '/swf/soundmanager2.swf',
preferFlash: false,
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'sonidos/sonido1.mp3' ,
autoplay: false
});
$("#stream").live("click", function(){
if (is_playing==false){
mySound.play();
is_playing = true;
}else if (is_playing== true) {
mySound.stop();
is_playing = false;
}
});
},
/* ontimeout: function() {
// Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
}*/
});
</script>
You have to use sound.stop();
There is also a built in function to toggle play/pause of a sound.
Use sound.togglePause(); to do that.
SC.stream("/tracks/13680213", function(sound) {
SC.sound = sound;
});
This means you aren't writing event listeners inside your SC.stream constructor then you can access the following (and more) at will:
SC.sound.play();
SC.sound.pause();
SC.sound.stop();
SC.sound.pause();
SC.sound.playState;
Since there are very few answers on this subject, I thought I would answer my own question.
I went ahead and downloaded Sound Manager 2 and placed the necessary files where they needed to be (you can find this in the basic tutorials section of the sound manager2 page.)
http://www.schillmania.com/projects/soundmanager2/demo/template/
The trick wass to locate the SoundCloud mp3 associated with the user I wanted to embed. To do this, I had to use a RESTClient and enter the appropriate api url.
It looks like this.
http://api.soundcloud.com/tracks/12758186.json?client_id={MyClient_ID_number}
The http://api.soundcloud.com/tracks/ is a general pointer to the track id="12758186". This is followed by the JSONP inclusion of my personal client_id to validate my request to the soundcloud server.
Once I had this url, I tried it in my browser and it redirected me to ** another url ** with an HTML5 mp3 player, which automatically played the song.
I got the idea to do this from this soundcloud doc:
http://developers.soundcloud.com/docs#playing
I then copied this url and mashed the code from my original question to the basic tutorial mentioned above (http://www.schillmania.com/projects/soundmanager2/demo/template/).
Final Code:
var is_playing = false;
$("#stream").live("click", function(){
soundManager.setup({
url: './swf/soundmanager2.swf',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: {**another url**},
autoplay: false
});
if (is_playing===false)
{
mySound.play();
is_playing = true;
}
else if (is_playing=== true)
{
mySound.stop();
is_playing = false;
}
},
ontimeout: function() {
// Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
}
});
});
Simply link the event which you would like to trigger the pause function to the "sound" object which is passed into SC.stream()'s callback function.
The form in the following code accepts a sound cloud link such as this one: https://soundcloud.com/djalmix-1/living-in-stereo-dj-almix (so paste that in to the form once the app is live and click load). Also you must provide your own client_id that soundcloud gives you when you register your app, this takes only a minute or so.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function load_sound() {
var track_url = document.getElementById("sc_url").value;
SC.initialize({
client_id: 'client_id'
});
SC.get('/resolve', {url: track_url}, function(track) {
console.log("the track id is: " + track.id);
SC.stream("/tracks/" + track.id, function(sound) {
var is_playing = true;
sound.play();
document.getElementById("stream").onclick = function(){
if(is_playing === false){
sound.resume();
is_playing = true;
} else if(is_playing === true){
sound.pause();
is_playing = false;
}
};
});
});
}
</script>
<form>
<input id="sc_url" type="url">
<input type="button" onclick="load_sound();" value="load">
</form>
<button id="stream">pause/resume</button>
</body>
</html>

Categories