I have tried to make it so when clicked play audio but this code doesn't work. I would also like to know how to implement this code that works.
javascript:(function(){ var style = document.createElement(%27style%27), styleContent = document.createTextNode(%27* { cursor: url(data:image/x-icon;base64,AAACAAEAICAAAA4AEACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwcGvpc3Ns/3NybP9vcGv/JSYt/xslI/8aJSP/FyUk/xkmJf8aJyX/Hygm/09OSv8iIiEEWFVhAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY1tlkRcfI/9fYWT/cnJr/1dbXf8aHyL/Ex4c/w0cGf8KGhr/CRoZ/w8aGv8SHhz/ISIf/yEhIP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHB4l/1tfZf9kaG7/NDc8/xYeIP8NHBv/Chwb/w0dHP8RHCH/Exsc/xUfHf8jIiP/IyIl/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgIij/XGFn/1pkaP8eJCf/FiAe/wkdGv8KHBr/DyIh/xokLP8UHB7/FyEg/yMjI/8lJCj/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABkmLP86P0X/XGRo/xsiKP8WIh7/CR0a/wscG/8SHR7/Eh0e/xQeHf8XISD/IiIi/ygnLfcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAABsg7n6Iz1y/xowYP8ZLFz/Gi9d/yIzZP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuTYX/EStZ/x43Z/8ZL2D/OE9//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHCEtlldd6/9Ok6D/3SGtrsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/4AH//8AA///gAP//4AD//+AA//+gAP//AAH//4AB//8AAf//AAAP/4AAB/+AAAf/AAAH/wAAB/8AAA//AAAf/wAAP/8AAH//gAB//8AAf//wAP//+Af///w////8P///+D////gf///4H///+B////gP///4H////B////4//8=javascript:(function(){ var style = document.createElement(%27style%27), styleContent = document.createTextNode(%27* { cursor: url() 22 22, auto !important}%27); style.appendChild(styleContent ); var caput = document.getElementsByTagName(%27head%27); caput[0].appendChild(style); })();) 22 22, auto !important}%27); style.appendChild(styleContent ); var caput = document.getElementsByTagName(%27head%27); caput[0].appendChild(style); })();
javascript:object.onclick = function(){var audio = new Audio('https://media1.vocaroo.com/mp3/12OdDSvf3CkE'); audio.play();};
This code doesn't work.
It appears you need to add an event listener for the canplay or canplaythrough event before calling audio.play(). Try this:
javascript: (function() { var audio = new Audio('https://media1.vocaroo.com/mp3/12OdDSvf3CkE'); audio.addEventListener('canplay', () =>{ audio.play(); });})();
A bit more readable:
(function() {
var audio = new Audio('https://media1.vocaroo.com/mp3/12OdDSvf3CkE');
audio.addEventListener('canplay', () =>{
audio.play();
});
})();
Edit: P.S. Nice choice of audio clip :)
Related
I am making a web app that can be open for a long time. I don't want to load audio at load time (when the HTML gets downloaded and parsed) to make the first load as fast as possible and to spare precious resources for mobile users. Audio is disabled by default.
Putting the audio in CSS or using preload is not appropriate here because I don't want to load it at load time with the rest.
I am searching for the ideal method to load audio at run time, (after a checkbox has been checked, this can be after 20 minutes after opening the app) given a list of audio elements.
The list is already in a variable allSounds. I have the following audio in a webpage (there are more):
<audio preload="none">
<source src="sound1.mp3">
</audio>
I want to keep the same HTML because after second visit I can easily change it to (this works fine with my server-side HTML generation)
<audio preload="auto">
<source src="sound1.mp3">
</audio>
and it works.
Once the option is turned on, I want to load the sounds, but not play them immediately. I know that .play() loads the sounds. But I want to avoid the delay between pressing a button and the associated feedback sound.
It is better to not play sound than delayed (in my app).
I made this event handler to load sounds (it works) but in the chrome console, it says that download was cancelled, and then restarted I don't know exactly what I am doing wrong.
Is this is the correct way to force load sounds? What are the other ways? If possible without changing the HTML.
let loadSounds = function () {
allSounds.forEach(function (sound) {
sound.preload = "auto";
sound.load();
});
loadSounds = function () {}; // Execute once
};
here is playSound function, but not very important for the questions
const playSound = function (sound) {
// PS
/* only plays ready sound to avoid delays between fetching*/
if (!soundEnabled)) {
return;
}
if (sound.readyState < sound.HAVE_ENOUGH_DATA) {
return;
}
sound.play();
};
Side question: Should there be a preload="full" in the HTML spec?
See also:
Preload mp3 file in queue to avoid any delay in playing the next file in queue
how we can Play Audio with text highlight word by word in angularjs
To cache the audio will need to Base64 encode your MP3 files, and start the Base64 encoded MP3 file with data:audio/mpeg;base64,
Then you can pre-load/cache the file with css using something like:
body::after {
content:url(myfile.mp3);
display:none;
}
I think I would just use the preloading functionality without involving audio tag at all...
Example:
var link = document.createElement('link')
link.rel = 'preload'
link.href = 'sound1.mp3'
link.as = 'audio'
link.onload = function() {
// Done loading the mp3
}
document.head.appendChild(link)
I'm quite sure that I've found a solution for you. As far as I'm concerned, your sounds are additional functionality, and are not required for everybody. In that case I would propose to load the sounds using pure javascript, after user has clicked unmute button.
A simple sketch of solution is:
window.addEventListener('load', function(event) {
var audioloaded = false;
var audioobject = null;
// Load audio on first click
document.getElementById('unmute').addEventListener('click', function(event) {
if (!audioloaded) { // Load audio on first click
audioobject = document.createElement("audio");
audioobject.preload = "auto"; // Load now!!!
var source = document.createElement("source");
source.src = "sound1.mp3"; // Append src
audioobject.appendChild(source);
audioobject.load(); // Just for sure, old browsers fallback
audioloaded = true; // Globally remember that audio is loaded
}
// Other mute / unmute stuff here that you already got... ;)
});
// Play sound on click
document.getElementById('playsound').addEventListener('click', function(event) {
audioobject.play();
});
});
Of course, button should have id="unmute", and for simplicity, body id="body" and play sound button id="playsound. You can modify that of course to suit your needs. After that, when someone will click unmute, audio object will be generated and dynamically loaded.
I didn't try this solution so there may be some little mistakes (I hope not!). But I hope this will get you an idea (sketch) how this can be acomplished using pure javascript.
Don't be afraid that this is pure javascript, without html. This is additional functionality, and javascript is the best way to implement it.
You can use a Blob URL representation of the file
let urls = [
"https://upload.wikimedia.org/wikipedia/commons/b/be/Hidden_Tribe_-_Didgeridoo_1_Live.ogg"
, "https://upload.wikimedia.org/wikipedia/commons/6/6e/Micronesia_National_Anthem.ogg"
];
let audioNodes, mediaBlobs, blobUrls;
const request = url => fetch(url).then(response => response.blob())
.catch(err => {throw err});
const handleResponse = response => {
mediaBlobs = response;
blobUrls = mediaBlobs.map(blob => URL.createObjectURL(blob));
audioNodes = blobUrls.map(blobURL => new Audio(blobURL));
}
const handleMediaSelection = () => {
const select = document.createElement("select");
document.body.appendChild(select);
const label = new Option("Select audio to play");
select.appendChild(label);
select.onchange = () => {
audioNodes.forEach(audio => {
audio.pause();
audio.currentTime = 0;
});
audioNodes[select.value].play();
}
select.onclick = () => {
const media = audioNodes.find(audio => audio.currentTime > 0);
if (media) {
media.pause();
media.currentTime = 0;
select.selectedIndex = 0;
}
}
mediaBlobs.forEach((blob, index) => {
let option = new Option(
new URL(urls[index]).pathname.split("/").pop()
, index
);
option.onclick = () => console.log()
select.appendChild(option);
})
}
const handleError = err => {
console.error(err);
}
Promise.all(urls.map(request))
.then(handleResponse)
.then(handleMediaSelection)
.catch(handleError);
I have a single link and I want the link to play different sounds each time it is clicked. When I click the link it plays both sounds at the same time but I want one sound at a time
var bleep = new Audio('hello.mp3') ;
bleep.src = "hello.mp3" ;
var bleep2 = new Audio('goodbye.mp3') ;
bleep2.src = "goodbye.mp3";
Home
You should make a function out of it that checks which sound was clicked last time. Also, you neither need to set the .src property or pass a string to the play method.
JS:
var bleep = new Audio('hello.mp3');
var bleep2 = new Audio('goodbye.mp3');
var playFirst = true;
function playSound() {
if (playFirst) {
bleep.play();
} else {
bleep2.play();
}
playFirst = !playFirst;
}
HTML:
Home
Instead of attaching the event listener inline as onclick, attach it with JS using addEventListener. This allows you to pick which audio clip to play:
var helloSound = new Audio('hello.mp3');
helloSound.src = "hello.mp3";
var goodbyeSound = new Audio('goodbye.mp3');
goodbyeSound.src = "goodbye.mp3";
var homeLink = document.getElementById('home-link');
homeLink.addEventListener('click', function () {
if (/* condition to play hello */) {
helloSound.play();
} else {
goodbyeSound.play();
}
});
Markup:
Home
I add a sprite that has eventListener to layer.When I touch it no error but no effect yet.
Here is my code:
onTouchBegan : function (event) {
var spriteFrames = [];
var frame = cc.spriteFrameCache.getSpriteFrame(res.stone_png);
var frame1 = cc.spriteFrameCache.getSpriteFrame(res.cloth_png);
spriteFrames.push(frame);
spriteFrames.push(frame1);
var animation = new cc.Animation(spriteFrames, 2, 30);
var action = cc.animate(animation);
action.retain();
clickSprite.runAction(
action
);
}
I make sure eventListener is no problem.Thanks for helps.Apologize for my English.
I am making a WebRTC application.
Basically I have this code:
rtc.onremotestream = function(event) {
//Want code to create a video tag in a specific <div> and then do this:
attachMediaStream([THAT NEW VIDEO TAG], event.stream);
}
How could I go about doing this? Autoplay needs to be true.
rtc.onremotestream = function(event) {
var videoTag = document.createElement('video');
document.getElementById('specific_div').appendChild(videoTag);
attachMediaStream(videoTag, event.stream);
}
Works?
I have create a javascript to change the audio after the audio ended.
var songlist = new Array("a.mp3", "b.mp3", "c.mp3", "d.mp3", "e.mp3", "f.mp3");
var dir = "music/";
var curr_track = 0;
var isfirstrun;
function start()
{
if(curr_track == songlist.length)
curr_track = 0;
var track = document.getElementById('track');
track.innerHTML = curr_track;
var audio = document.getElementById('audio');
isfirstrun = true;
audio.src = dir+songlist[curr_track];
audio.load();
audio.play();
if(isfirstrun == true)
{
audio.addEventListener('ended', function(){ curr_track++; start();}, false);
isfirstrun = false;
}
}
And inside the HTML,
<body onload="start();">
The track used in the code is to show what is the current track number, and I found out that the output is
0 then 1 then 3 then 7
Hence, it is missing c.mp3, e.mp3 and f.mp3 from the songlist.
How can I solve the problem of the looping?
Every time the song ends, you are adding another event handler. This is why you see +1, +2, +4 etc. because the number of event handlers doubles each time around.
This is the main reason why I prefer to use audio.onended = function() {curr_track++; start();};
But anyway, to fix this all you have to do is have an "isfirstrun" variable, starting at true, then only add the event listener if it is true and set it to false.