Play MP3 on touch event with HTML-CSS-JS - javascript

could someone help me in finding a way to play an mp3 audio file by touching an image on a touch screen with HTML-CSS-JavaScript?
Thank you!

<!DOCTYPE HTML>
<html>
<head>
<title>audio with image</title>
</head>
<body>
<script>
function play(){
var audio = document.getElementById("audio");
audio.play();
}
</script>
<img src="http://www.partyplan123.com/wp-content/uploads/2015/02/click-here.jpg" onclick="play()">
<audio id="audio" src="http://kolber.github.io/audiojs/demos/mp3/juicy.mp3" ></audio>
</body>
</html>

To play an audio file in HTML, use the <audio></audio> tag.
This tag also comes with <audio controls> attribute, to add controls like play pause and all.
For a full DOM documentation on this tag go to the W3 audio tag docs
As for the JS side, use the onclick() event for triggering the audio file on touch.

Create an audio element in your html and hide it using visibility: hidden.
When the user clicks on the image, handle the click event with Javascript and trigger play on the audio element manually from the handler.
You can refer here for more documentation on audio html api's.

Here's the best way. This is not inline Javascript so complies to Content Security Policies (CSP's) so if you port to android .apk or to a chromium app, you won't have issues. This is not my code obviously, its from Steven Park on teamtreehouse:
The first way using Jquery:
const rollSound = new Audio("./assets/audio/ONEDICE.WAV");
$('#dice-button').click(e => rollSound.play());
Create a a div with the #div-button name, and also another example a version that is not JQuery:
const rollSound = new Audio("./assets/audio/ONEDICE.WAV");
document.getElementById('dice-button').addEventListener("click", e =>
rollSound.play());
You can find it here:
https://teamtreehouse.com/community/how-do-i-add-a-sound-when-a-button-is-clicked-jquery
However I have cut and paste it because it took me hours to find that solution after searching for something that fills my needs.

Related

How do I get an audio snippet to play when hovering over an image element?

After too many hours on YT and Google, I'm here. Thanks for taking the time to read & help. :)
I'm trying to make it so that when the mouse hovers over the image, an audio snippet plays automatically. I've tried a few different things, but this is where I stopped.
Can't seem to get anything to work.
HTML file snippet
<head>
<link rel="stylesheet" href="./stylesheet.css">
<script type="text/javascript" src="./scripts.js"></script>
...other stuff etc etc
<div class="deviruchi" data-tooltip="no touchy!">
<audio id="devi">
<source src="./sounds/deviruchi_idle.mp3">
<source src="./sounds/deviruchi_idle.ogg">
</audio>
<img src="./images/deviruchi.gif">
</div>
Javascript file
let deviruchi = $("#devi")[0];
$(".deviruchi").onmouseenter(function () {
deviruchi.play();
});
Thanks again! :)
Probably because you are using jquery...(j/k, but no really)
Make sure that the audio files are present on the server, check devtools for error messages (javascript as well as network)
Also, user must first interact with the webpage (click/focus, etc) before browser will allow play media files.
hoverMe.addEventListener("mouseenter", e =>
{
myAudio.play().catch(er => console.error(er.message, "Now, click here and try again"));
});
hoverMe.addEventListener("mouseleave", e =>
{
myAudio.pause();
});
<div id="hoverMe">Hover over here</div>
<audio id="myAudio" src="https://sample-videos.com/audio/mp3/crowd-cheering.mp3"></audio>

HEAD tags interfering with base64 in PhoneGap ??? Even when nothing is in the Head? base 64

This is the strangest programming issue I've ever come across... I'm working on a program that uses some audio encoded as base64. They are small audio files (less than 2k each) Here's a simplified version. If you run this exactly as is in your browser, you'll see a button that plays a click sound when pressed. GET READY FOR THE CRAZY PART.... I put this into phonegap and it didn't work... UNLESS I remove the two head tags <head> and </head> Try it, put the code into an html file called index.html and try it in phonegap. You'll see the button, but it won't play. But if you try it without the head tags it will play the click sound. Someone please explain!
function snd(s) {
aud = new Audio();
aud.src = document.getElementById(s).src;
aud.load();
aud.volume=1;
aud.play();
}
button {width:200px;height:60px;margin:20px}
<html>
<head>
</head>
<body>
<audio id="click" src="data:audio/mp3;base64,SUQzAwAAAAAAFgAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/82hQAAMoAu4AoAAAAKgCXK1AAAD/////+fKOOL///////hgTnwQKO///cXPk/4AAtASxAAAGQAAA3uMqQaQZUlUmU3Y65ndJ5vNy3f0ru8ckC8YWKEkV6dJ5Y7gl+mG27BlmS39csG5iMKANO2MNOb12M+28OKSL4IgJUg5agwsMiY47JsN9z1wVOEXUAVuaCgDSHA9VIgwIKgTJ5/9/+q2qvTAFjhQgOggTcVubuNDShuLF/vf///yzhdBJwvQ7bLUx3XWJHG6Q48LQ60AQVOfzn/////3/82hwnSYaI1+Px+AAASACXK2AAAB9Uf09TKVLtDSKu/QtEToVsnFg5YrttYGl8NzbdHgkP/z/5/4b/v/xVUMG8uTDx4AVSdRrpQQF6FHGmphrlh99GvRh+5ZLlO3dkboNehyX2P//5h///////c9cSviEDOoxMDQTtSTeNylYAENS+H0T1PpEJ5ISH9nHRqP89E1D2fvlE4zSyncppMMJP//////er95H///gAACyFEpMpJNTv/9tySSa67hNVvoIAdQz4sgPYS51Pc6dHcUyROGxOWfrTFr/82hwKhNZlWcrxDQAASACXK2AAAAMIXURJUUnRRnzZ0XJcmCaDDEpUpIyUpBzRE+ZUzEcpsSakzEvF6Y+1zQ6o3OIF4eSRrWqk/1IJ2pHy8mcZzq1mKCnW2+ivt6KqnTQdmSHsPJAxKrHTZJJFlautq93b1+o+GglUPPQECtg7xczY2/1J///4AAAkxFJk/HHVXbakkltIlnkR8knAUkdeqVZnkKPT11OZYuCKs2rDL9QsMMBVrd25Xxoi3atcSrWHFU3jRntKwmuuv/Xefn33C3quL4zrH//82hwTRah5WkbxDwCASACXK2AAAD8CJLPS2dxt1/1WLm3//+M+J399vPSk2q7o9rXFpGF6frF8Y//x//fbPveI9I0TVpWdUEqIVVSmjCYkO+rQU6y4//+cZ//+MUozxuwa+NUfv47yms775PQWFDbWhV1a0sCDXFaweKfFP//+AAA//////////////////////////4AQLAggQf/////////////////////////////////////////////////////////////////////////////////82hQVgJgAS4A4AAAAcACXOnAAAD////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/82hQ/xgAAS4AAAAAAKgCXKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="></audio>
<button onclick="snd('click')">click</button><br><br>
</body>
</html>

using an external script page for my page which needs multiple scripts

I am currently making a page for educational purposes. Now i am making a page which contains multiple buttons that contain the function that when u click them, that they will play music. now i need 10 of these under eachother. But I have 10 different sound fragments. If i put 10 different scripts underneath eachother, that will make an absolute mess and I was wondering if it was possible to have those scripts together in an other file. Or is there an easier way to do it? I have this idea that this can be a lot easier.
this is the script and html I use.
<script>
function playMusic (){
var audio = document.getElementById("geluidsopname");
audio.play();
}
</script>
<button id="voortgang-button" onclick="playMusic()" value="button">
<img id="afspeelbutton" src ="../../../image/afspeelbutton1.png"> </img>Ik heet Marie.
<audio id="geluidsopname" src="../../../voice-recording/Marie.mp3"></audio>
</button>
You don't necessarily need to assign every element a unique id, you can access them through different methods. Take a look at document.querySelector, for example.
Calling a JS function from within an HTML event attribute is fine, but not recommended. Registering an event directly on your JS code is much cleaner.
You may want to put a single script just before the body's closure, or eventually put it in the head and execute it on DOMContentLoaded.
<button class="myBtn" id="button1">
<img src="url">
<audio>
<source src="url" type="audio/mpeg">
Your browser does not support the audio feature.
</audio>
</button>
<script type="text/javascript">
for (var aud in document.querySelectorAll('.myBtn')) {
aud.addEventListener('click', function() {
aud.querySelector('audio').play();
}, false);
}
</script>
Of course, you could just add the controls attribute to the audio element and have all events related to audio controls handled by the browser:
<button class="myBtn">
<img src="url">
<audio controls>
<source src="url" type="audio/mpeg">
Your browser does not support the audio feature.
</audio>
</button>
Here is a plunker of the code. I've modified a bit the html structure for the demo. Still the idea is there: your script uses parameter.
// Code goes here
function playMusic ( target ){
console.log(target.getAttribute("target_audio"))
var audio = document.getElementById( target.getAttribute("target_audio") );
audio.play();
}
And html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<input type="button" id="voortgang-button" target_audio="geluidsopname" onclick="playMusic( this )" value="button">
<img id="afspeelbutton" src ="../../../image/afspeelbutton1.png">Ik heet Marie.
<audio id="geluidsopname" src="../../../voice-recording/Marie.mp3"></audio>
</body>
</html>
If you like, you can pass id as a string, to the handler method. Then you dont need to get attribute's value even.

How to use Soundcloud api to get stream into html5 audio player?

I've just started learning javascript and as my first attempt I'd like to create custom audio player which uses soundcloud's api as a source for music.
So far this is what I got set up:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
window.onload = function() {
SC.initialize({
client_id: '10e27db0dacd00954d7160b4c092a6e2' //Demo ID
});
SC.stream("/tracks/75868018", function(sound){
$("audio-test").attr("src", sound.uri);
});
};
</script>
</head>
<body>
<audio id="audio-test" controls></audio>
</body>
</html>
Ok, got it figured out. The problem was the .stream() - it's meant to deliver a prepackaged player, deployed by the .play() function.
If you use SC.get() instead, you'll actually access the properties of the track, and be able to embed it in an audio tag. See my code: http://jsfiddle.net/LpzpK/6/
There's still a problem - the tracks are marked as 401 forbidden, so the player is only ever "Loading". You'll have to find a way to make the tracks you want to play public.
At a cursory glance, it looks like all soundcloud API objects come with a URI property that links directly to the resource. In your case, it would be sound.uri.
At the top of your player code, you have an <audio> tag - my guess is you'll want to set it's src to the URI value for the track you're playing. You can do this by attaching an ID to it and calling
SC.stream("/tracks/293", function(sound){
$("[audio_id]").attr("src", sound.uri);
});
replacing [audio_id] with whatever ID you choose for the tag. You'll probably still have to do something to reinitialize/restart the player each time it changes, but that will hopefully get you started. Let me know how it works!

Jquery TubePlayer Plugin not functioning as desired

TubePlayer is a jQuery Plugin that implements YouTube Player API, and allows us to create our own controls and components for YouTube videos.
The TubePlayer Website provides tips on getting started with it.
However, this is not working for me. This page on its site demonstrates a quick start guide. I followed exactly what it specified but does not work.
The video plays fine, but somehow the links to control the video do not work.
Is there anything wrong with the code. If you wanna try it out, here's the code :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script src="http://www.tikku.com/scripts/ui/tubeplayer/jQuery.tubeplayer.min.js"></script>
<script>
$(function(){
jQuery("#youtube-player-container").tubeplayer({
width: 600, // the width of the player
height: 450, // the height of the player
allowFullScreen: "true", // true by default, allow user to go full screen
initialVideo: "ylLzyHk54Z0", // the video that is loaded into the player
preferredQuality: "default",// preferred quality: default, small, medium, large, hd720
onPlay: function(id){}, // after the play method is called
onPause: function(){}, // after the pause method is called
onStop: function(){}, // after the player is stopped
onSeek: function(time){}, // after the video has been seeked to a defined point
onMute: function(){}, // after the player is muted
onUnMute: function(){} // after the player is unmuted
});
}) ;
</script>
</head>
<body>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("play")'>
Play
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("pause")'>
Pause
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("stop")'>
Stop
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("mute")'>
Mute
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("unmute")'>
Unmute
</a>
<div id='youtube-player-container'> </div>
</body>
</html>
Can anyone help me out please. Thanks.
Sorry for the above question, my bad. I found out the problem, just noticed that in the API docs page. As stated in the documentation, we need to be on a web server with the test script. No idea, how i missed that section. Need to concentrate more often while reading in the future.
I quote the very documentation page:
" Any HTML page that contains the YouTube player must implement a JavaScript function named onYouTubePlayerReady. The API will call this function when the player is fully loaded and the API is ready to receive calls.
Note: To test any of these calls, you must have your file running on a webserver, as the Flash player restricts calls between local files and the internet. "
The above code works fine. Thanks.

Categories