JColling
JColling

Reputation: 149

Reference URL with JavaScript to play sound?

Im using soundcloud dot com to upload my sounds. i want to press a button within my mobile application and have that sound play.

So basically i want my sound to be referenced from the URL that I am given when the button is pressed by the user.

I need to do it with Javascript only. No HTML 5 please. Any help is greatly appreciated cause this is Xtremely frustrating. Any ideas? Thanks in advance.

Upvotes: 12

Views: 41269

Answers (3)

Mostafa Mohammadzadeh
Mostafa Mohammadzadeh

Reputation: 911

let sound = new Audio("http://sound.com/mySound.mp3");

//on play event:
sound.onplay = () => {

};

//on pause event:
sound.onpause = () => {

};

//on end event:
sound.onended = () => {

};

//play:
sound.play();

//pause:
sound.pause();

//stop:
sound.pause();
sound.currentTime = 0;

Upvotes: 2

Larry Battle
Larry Battle

Reputation: 9178

Use jPlayer to play sound using Javascript. This will take you a lot of time and frustration.

jplayer.org/

Here's what your code might look like with jPlayer. Note: You're not forced to use a skin with jPlayer because all it is is just an API to play audio.

Example code to play a video or audio on load.

$(function() { // executed when $(document).ready()
  $("#jpId").jPlayer( {
    ready: function () {
      $(this).jPlayer("setMedia", {
        m4v: "http://www.myDomain.com/myVideo.m4v" // Defines the m4v url
      }).jPlayer("play"); // Attempts to Auto-Play the media
    },
    supplied: "m4v",
    swfPath: "jPlayer/js"
  });
});

http://jplayer.org/latest/developer-guide/

Upvotes: 0

nickf
nickf

Reputation: 546025

It's pretty simple to get started really:

function playSound(url) {
    var a = new Audio(url);
    a.play();
}

Use that as whatever event handler you want for your application. Of course, I'd hope you'd want to do more than just play (for example, maybe pause would be good too?), but it's a start.

Upvotes: 38

Related Questions