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

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!

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>

I'm having some trouble with the .play function in javascript

I have been trying to use audio in some new games I am making, and I have absolutely everything set up correctly, as it is a very easy program. The audio plays fine with the controls on, but I want to figure out how play it with Javascript, so a player event can trigger the sound.
I have tried:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>audio?</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<audio id='test'>
<source src='test.mp3' type='audio/mpeg'>
sorry
</audio>
<script>
var myAudio=document.getElementsByName('test');
myAudio.play();
</script>
</body>
</html>
Again, a very simple code and the error message I am getting is:
TypeError: myAudio.play is not a function.
Can anyone help with the issue?
You should review the documentation for Document.getelementsByName(), as it seems you have two misunderstandings about its proper use:
The linked documentation points out that a successful call returns either a NodeList or an HTMLCollection object, both of which do not have any method play(). You seem to think that this method instead will return a single Node, which is not the case.
The linked documentation also makes light of the fact that it will target elements by their name attributes. You haven't used a name attribute in any of the elements you provided in your HTML - the id you seem to want to reference is absolutely not the same as a name.
(This is only untrue for Internet Explorer 10 and below, where elements would be returned if either the id or name values matched the value of the parameter you pass. However, relying on this non-standard behavior isn't a great practice to take up, especially considering IE's dwindling market share.)
In this scenario, where you are confident there will only ever be one element with the ID of test, you may wish to instead use Document.querySelector() instead (which returns the Node you're seemingly looking for):
var myAudio=document.querySelector('#test');
myAudio.play();
Alternatively, Document.getElementById() would also work in this scenario:
var myAudio=document.getElementById('test');
myAudio.play();

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>

Play MP3 on touch event with HTML-CSS-JS

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.

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