How to check whether a sound file is playing in JavaScript - javascript

var soundObject = null;
function PlaySound() {
var textvalue = document.getElementById('<%= TextBox7.ClientID %>').value;
if (soundObject != null) {
document.body.removeChild(soundObject);
soundObject.removed = true;
soundObject = null;
}
soundObject = document.createElement("embed");
soundObject.setAttribute("src", textvalue);
soundObject.setAttribute("hidden", false);
soundObject.setAttribute("autostart", true);
document.getElementById("div1").appendChild(soundObject);
Above is my javascript code, TextBox7.text="c:\temp\abc.wav" in c#. I have two questions:
1. Is there anyway to tell whether the file c:\temp\abc.wax exists before playing the audio file?
2. How to check if the file start playing or not (since I put autostart)?
My intention is to alert user if the file does not exist or not playing?
PS: Actually, the program is working, it will play the audio when file exists and show a blackscreen if the audio file not found. I just want to make it better so that the user know what is going on.

The <embed> element does not give you that level of control over the audio file being played. If you are able to, I would strongly encourage using the HTML5 <audio> element instead. It inherits from the HTMLMediaElement Dom interface which gives you access to a lot more media specific data. The <embed> element only inherits from the HTMLElement which does not give the same level of control.
You can change your above code to be:
soundObject = new Audio();
soundObject.src = textValue;
soundObject.hidden = true;
soundObject.autoplay = true;
document.getElementById("div1").appendChild(soundObject);
soundObject.play();
Once you do that if you get an error on playback you can use soundObject.error to access the error message. This will give you an error if the file doesn't exist or any other error during playback.
To tell if the file is actively playing you can monitor the soundObject.played to see what part of the file has already been played.
I hope this solves your problem for you!
Edit:
I am attaching a JSFiddle that will hopefully give you a better idea of how to use this feature here.

Related

Can't use a try/catch to test if audio is valid in Javascript

I have a form that lets users change the default sound notification and I'm now trying to validate the audio link the user submits. The default sound, which I created with a normal HTML element (document.createElement) plays audio fine. When I run the following code (where inp represents a text input and audio represents the original audio object), I get an unsupported source DOM error:
try {
let newAudio = document.createElement("audio");
newAudio.src = inp.value;
newAudio.play();
audio = newAudio;
}
catch(e) {
alert(e);
}
I've tried all kinds of variations but nothing seems to work: creating newAudio as a JS audio object, reading the duration/readyState value of the audio object, etc. Again, nothing works and I'm not sure why.

Javascript get updated link in real time

I'm new to javascript and I've created a kinda successful extension on chrome for dubtrack I've been trying to figure out for quite awhile how to make my injected script run in real time and grab the latest youtube music video url any help would be much appreciated my extension is very basic and it's not for profit I just made it to play around with javascript and jquery.
Here's the section of code that I'd like to have function in real time.
$('#grab').click(function() {
function getId(url) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
return 'error';
}
}
src = $('iframe').attr('src');
setInterval(function() {
src = $('iframe').attr('src');
}, 10000);
window.open('http://youtubeinmp3.com/fetch/?video=http://www.youtube.com/watch?v=' + getId(src), '_blank');
});
Relevant links
GitHub
Chrome Extension
Thank you for taking the time to read my question.
You're bad at explaining (and might want to edit the question to reflect what you want), but basically the problem is this:
You have a YouTube embed in the page, with a particular video ID in src.
When the video changes, that happens without updating the src (by using YT embed API).
Therefore, if you try to grab just the src, it's not the latest video but the first you loaded.
As an extension, I see two ways of trying to solve it:
You could try to initialize the YT API yourself to get a player reference. I don't know if it will break the code of Dubtrack.
You could inject a script in the iframe as well that would somehow extract the video being played in a way other than relying on src.
It's an open problem how to solve it, and the fact that you're basically providing "just" a bookmarklet may be an obstacle.

How to determine if playing HTML5 audio is actually making sound?

For the purposes of a project I am working, I want to find out via the JS console if the <audio> tag found on facebook.com is playing audio or not. (I can then move this code into a Chrome extension and also apply it against other websites such as silent HTML5 ads.)
You can find the element by typing:
$$("audio")[0]
I have used the following code (adapted from this jsfiddle which I found during a search) to show when different event listeners are called:
var audio = $$("audio")[0];
var events = 'abort,canplay,canplaythrough,durationchange,emptied,ended,error,loadeddata,loadedmetadata,loadstart,pause,play,playing,progress,ratechange,seeked,seeking,stalled,suspend,timeupdate,volumechange,waiting'.split(',');
// event handler
var onEvent = function(e) {
console.log(e.type);
};
// add event listener to audio for all events
for (var i = 0, len = events.length; i < len; i++) {
audio.addEventListener(events[i], onEvent, false);
}
I would then play the audio by typing:
$$("audio")[0].play();
If I check $$("audio")[0].paused, it will show false, but I haven't found any properties or events that would indicate whether it played sound or not. (I wouldn't expect it to here since I don't think it has audio data to play, but if there was a way to check, I could compare that with an audio element that does play sound.)
Also, I have tried sending myself a message from an incognito tab and don't see a trace of this happening. (I assume the audio element gets used for that.)
Help is appreciated.
To check if an HTMLMediaElement (either video or audio) has ever been played on the page, the best solution is to check for its played attribute.
This will return a TimeRanges object that you can as well use to get how much of the media has been played.
If it has never been played, then the length property of this TimeRanges object will be set to 0 :
if(audioElement.played.length){
// This media has already been played
}else{
// Never
}

Stopping an audio element by ID

Thanks for checking out my question. I'm running into a stumbling block stopping an audio element and I'm hoping to get some help. I'm creating audio elements dynamically with arguments, like this.
var audio = document.createElement("audio");
audio.setAttribute('id', params[0]);
This works fine, params[0] is a user argument. I can alert audio.id and I get 'backgroundmusic' for example. And audio.play works. The problem comes when I try to stop it.
var audio = document.getElementById(params[0]);
audio.pause();
I thought this would work, but it returns null every time. I'm a total javascript rookie and Im sure this is a rookie mistake, but what am I doing wrong?
Thank you very much in advance.
After creating the audio element, append it to some element in the dom.
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'http://home.tiscali.nl/~jvanderw/malaysia02/sounds/greatargus.mp3');
audioElement.setAttribute('id', "user_id");
audioElement.load()
$("#audio_div").append(audioElement);
I created a fiddle, check this http://jsfiddle.net/QG68M/
I had observed that you did not attached the audio object to the DOM/Document. This causes document.getElementByID to fail in finding the element. the easiest way to stop the audio file from playing is to keep a reference to the audio object that you created.
var audioControl;
function CreateAudioElement(params)
{
audioControl = document.createElement("audio");
audioControl.setAttribute('id', params[0]);
}
function StopAudioElement()
{
audioControl.pause();
}

JS .play() on iPad plays wrong file...suggestions?

So, I am building a web app that has a div with text that changes on various user actions (it's stepping through an array of pieces of text). I'm trying to add audio to it, so I made another array with the sound files in the appropriate positions:
var phrases=['Please hand me the awl.','etc1','etc2','etc3'];
var phrasesAudio=['awl.mp3','etc1.mp3','etc2.mp3','etc3.mp3'];
And on each action completion, a 'counter' variable in incremented, and each array looks for the object at that counter
var audio = document.createElement("audio"),
canPlayMP3 = (typeof audio.canPlayType === "function" &&
audio.canPlayType("audio/mpeg") !== "");
function onAction(){
correct++;
document.getElementById('speech').innerHTML=phrases[correct];
if(canPlayMP3){
snd = new Audio(phrasesAudio[correct]);
}
else{
snd = new Audio(phrasesAudioOgg[correct]);
}
snd.play();
}
(the text replaces a div's HTML and I use .play() for the audio object)...usually works okay (and ALWAYS does in a 'real' browser), but on the iPad (the actual target device) after a few successful iterations, the TEXT continues to progress accurately, but the AUDIO will hiccup and repeat a sound file one or more times. I added some logging and looking there it reports that it's playing screw.mp3 (just an example, no particular file is more or less error prone), but in actuality it plays screwdriver.mp3 (the prior file, if there is an error, the audio always LAGS, never LEADS)...because of this I am thinking that the problem is with my use of .play()...so I tried setting snd=null; between each sound, but nothing changed...Any suggestions for how to proceed? This is my first use of audio elements so any advice is appreciated. Thanks.
edit: I've also tried setting the files with snd.src (based on https://wiki.mozilla.org/Audio_Data_API) and this caused no audio to play
for iPad you need to call snd.load() before snd.play() - otherwise you get "odd" behaviour...
see for some insight:
http://jnjnjn.com/187/playing-audio-on-the-ipad-with-html5-and-javascript/
Autoplay audio files on an iPad with HTML5
EDIT - as per comment from the OP:
Here https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox you can find a tip on halting a currently playing piece of media with
var mediaElement = document.getElementById("myMediaElementID");
mediaElement.pause();
mediaElement.src = "";
and, following that with setting the correct src, load(), play() works great

Categories

Resources