Setup a clearkey server for shaka player didn't work? - drm

I've created a test html page for playing a MPEG-CENC protected MPEG-DASH video, and I can play if I specify kid: key pair in player.configure().
Then I want to setup a clearkey server. Refer to DRM Configuration section of Shaka Player documents, I changed the code to specify the url to get the license like below. But the page never get touched when I set a breakpoint in Page_Load event in Visual Studio. There is no error on console of browser.
The browser I use is Firefox 53.0.2 and Chrome 58.0.3029.96. Did I miss something?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/shaka-player/2.1.0/shaka-player.compiled.js"></script>
<title>MPEG-DASH Player Test</title>
<script>
//MPEG-DASH stream encrypted with MPEG-CENC:
var manifestUri = '/dashtest_encrypted/stream.mpd';
function initApp() {
// Install built-in polyfills to patch browser incompatibilities.
shaka.polyfill.installAll();
// Check to see if the browser supports the basic APIs Shaka needs.
if (shaka.Player.isBrowserSupported()) {
// Everything looks good!
initPlayer();
} else {
// This browser does not have the minimum set of APIs we need.
console.error('Browser not supported!');
}
}
function initPlayer() {
// Create a Player instance.
var video = document.getElementById('video');
var player = new shaka.Player(video);
// Configue
player.configure({
drm: {
servers: {
'org.w3.clearkey': '/clearkey/GetLic.aspx'
},
clearKeys: {
//'kid': 'key'
}
}
});
// Attach player to the window to make it easy to access in the JS console.
window.player = player;
// Listen for error events.
player.addEventListener('error', onErrorEvent);
// Try to load a manifest.
// This is an asynchronous process.
player.load(manifestUri).then(function () {
// This runs if the asynchronous load is successful.
console.log('The video has now been loaded!');
}).catch(onError); // onError is executed if the asynchronous load fails.
}
function onErrorEvent(event) {
// Extract the shaka.util.Error object from the event.
onError(event.detail);
}
function onError(error) {
// Log the error.
console.error('Error code', error.code, 'object', error);
alert(error.code);
}
document.addEventListener('DOMContentLoaded', initApp);
</script>
</head>
<body>
<video id="video" autoplay controls></video>
</body>
</html>
Here is the content of stream.MPD:
<?xml version="1.0" ?>
<MPD mediaPresentationDuration="PT12M3.022S" minBufferTime="PT15.48S" profiles="urn:mpeg:dash:profile:isoff-live:2011" type="static" xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:cenc="urn:mpeg:cenc:2013">
<!-- Created with Bento4 mp4-dash.py, VERSION=1.7.0-614 -->
<Period>
<!-- Video -->
<AdaptationSet maxHeight="720" maxWidth="1280" mimeType="video/mp4" minHeight="720" minWidth="1280" segmentAlignment="true" startWithSAP="1">
<!-- MPEG Common Encryption -->
<ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
<SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
<Representation bandwidth="1901600" codecs="avc1.64001F" frameRate="30000/1001" height="720" id="video/avc1" scanType="progressive" width="1280"/>
</AdaptationSet>
<!-- Audio -->
<AdaptationSet mimeType="audio/mp4" segmentAlignment="true" startWithSAP="1">
<!-- MPEG Common Encryption -->
<ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
<SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
<Representation audioSamplingRate="44100" bandwidth="200442" codecs="mp4a.40.2" id="audio/und/mp4a">
<AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
</Representation>
</AdaptationSet>
</Period>
</MPD>

After a very long time testing and comparison, I noticed that my .mpd file didn't have cenc:pssh tag, which resulted this problem. I recreated the .mpd and Shaka Player FINALLY asked the server.
The corrected .mpd is below:
<?xml version="1.0" ?>
<MPD mediaPresentationDuration="PT12M3.022S" minBufferTime="PT15.48S" profiles="urn:mpeg:dash:profile:isoff-live:2011" type="static" xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:cenc="urn:mpeg:cenc:2013">
<!-- Created with Bento4 mp4-dash.py, VERSION=1.7.0-614 -->
<Period>
<!-- Video -->
<AdaptationSet maxHeight="720" maxWidth="1280" mimeType="video/mp4" minHeight="720" minWidth="1280" segmentAlignment="true" startWithSAP="1">
<!-- EME Common Encryption -->
<ContentProtection schemeIdUri="urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b" value="cenc">
<cenc:pssh>AAAANHBzc2gBAAAAEHfv7MCyTQKs4zweUuL7SwAAAAF6ThLxhhApHzhsesG5Qlq/AAAAAA==</cenc:pssh>
</ContentProtection>
<!-- MPEG Common Encryption -->
<ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
<SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
<Representation bandwidth="1901627" codecs="avc1.64001F" frameRate="30000/1001" height="720" id="video/avc1" scanType="progressive" width="1280"/>
</AdaptationSet>
<!-- Audio -->
<AdaptationSet mimeType="audio/mp4" segmentAlignment="true" startWithSAP="1">
<!-- EME Common Encryption -->
<ContentProtection schemeIdUri="urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b" value="cenc">
<cenc:pssh>AAAANHBzc2gBAAAAEHfv7MCyTQKs4zweUuL7SwAAAAF6ThLxhhApHzhsesG5Qlq/AAAAAA==</cenc:pssh>
</ContentProtection>
<!-- MPEG Common Encryption -->
<ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
<SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
<Representation audioSamplingRate="44100" bandwidth="200442" codecs="mp4a.40.2" id="audio/und/mp4a">
<AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
</Representation>
</AdaptationSet>
</Period>
</MPD>

Related

Automating click to image-mapped actions/links using Node/Nightwatch

How does one use NightwatchJs to automate clicking a specific part of an image? My naive approach is to select the coords attribute that matches the specific area of the image I'd like to trigger; but it doesn't work.
<img src="..." usemap="#example">
<map name="example" id="example">
<area shape="rect" coords="336,10,401,32" href="...">
<area shape="rect" coords="25,171,97,198" href="...">
...
</map>
Anyone encounter this issue or know of a work around? Thanks!
If I were you, I would play with the position of area elements inside the map element using CSS selectors like :first-child or :first-of-type. Here is a minimal working example:
PNG (map.png)
HTML/JS (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Nightwatch</title>
</head>
<body>
<img src="map.png" usemap="#map">
<map name="map">
<area shape="circle" coords="51,51,29">
</map>
<script>
// When the red area is clicked, we should display an alert.
var area = document.querySelector('area');
area.addEventListener('click', function () {
alert('OK');
}, false);
</script>
</body>
</html>
Nightwatch (script.js)
module.exports = {
'Clickable image map': function (browser) {
browser
.url('http://localhost:8000/index.html')
.waitForElementPresent('map', 1000)
.click('map > area:first-child');
// ...
},
};
Command
If your environment is properly set up, you can run the script with nightwatch -t tests/script.js. You will see the alert, meaning that the red area has been clicked by Nightwatch.

How to trigger audio and skybox image/video sphere at the same time by clicking?

AFRAME.registerComponent('set-sky', {
schema: {default:''},
multiple: true
init() {
const sky = document.querySelector('a-sky');
this.el.addEventListener('click', () => {
sky.setAttribute('src', this.data);
});
}
});
Trying to modify this component so it can play a different audio each time I change the skybox picture through clicking. Any suggestions how that could be done?
Also, is there any chance I might be able to use both images and video spheres in a component like this? Thanks!
<html>
<head>
<script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
<script src="https://rawgit.com/aframevr/aframe/2baa063/dist/aframe-master.min.js"></script>
<meta charset="UTF-8">
<script>
AFRAME.registerComponent('set-sky', {
schema: {default:''},
init() {
const sky = document.querySelector('a-sky');
this.el.addEventListener('click', () => {
sky.setAttribute('src', this.data);
});
}
});
</script>
</head>
<body>
<a-scene>
<a-assets>
<audio id="opening" src="Lake Ambience.mp3"></audio>
<audio id="1" src="Game.wav"></audio>
<audio id="2" src="Explosion.wav"></audio>
<audio id="3" src="Laser.wav"></audio>
<audio id="4" src="Spooky.mp3"></audio>
<video id="video" src="Video.MP4"></video>
</a-assets>
<!-- Sounds -->
<a-entity sound="autoplay: true; loop: true; src: #opening;"></a-entity>
<a-camera position="0 2 0">
<a-cursor color="#5DADE2" fuse="true" timeout="10"></a-cursor>
</a-camera>
<a-sphere color="#2C3E50" radius="0.5" position="0 -5 -15" set-sky="1.jpg"></a-sphere>
<a-sphere color="red" radius="0.5" position="-15 -5 0" set-sky="2.jpg"></a-sphere>
<a-sphere color="blue" radius="0.5" position="15 -5 0" set-sky="3.jpg"></a-sphere>
<a-sphere color="white" radius="0.5" position="0 -5 15" set-sky="4.jpg"></a-sphere>
<a-sky></a-sky>
</a-scene>
</body>
</html>
This is what I have right now, and I'm trying to add sound to each of the sphere click event, while changing "4.jpg" to a 360 video in the last event.
You can change the audio each time with your 'click' event that you have already set up.
const sky = document.querySelector('a-sky');
const entity= document.querySelector('a-entity');
var image = this.data.substring(0,1) // this grabs the jpg file id to reference the audio asset id
this.el.addEventListener('click', () => {
sky.setAttribute('src', this.data);
entity.setAttribute('src', "autoplay: true; loop: true; src: #" + image + ";");
});
This probably isn't the best way for you to do this. If you want different combinations of images and audio files, then you should need to add a new scheme value for the component to reference the audio files.

MPEG-DASH cannot decrypt mp4 with clearkey

i have an audio-only mp4 file encrypted with MP4Box, with command MP4BOx -crypt drm.xml audio-only.mp4 -out audio-only-enc.mp4
This is drm.xml:
<GPACDRM type="CENC AES-CTR">
<DRMInfo type="pssh" version="0">
<BS ID128="9A04F07998404286AB92E65BE0885F95"/>
<BS data="application/data;base64:ACE125"/>
<BS sourceFile="cenc_blob.bin"/>
</DRMInfo> <DRMInfo type="pssh" version="1" cypherOffset="9" cypherKey="0x6770616363656E6364726D746F6F6C31" cypherIV="0x00000000000000000000000000000001">
<BS ID128="6770616363656E6364726D746F6F6C31"/>
<BS value="2" bits="32"/>
<BS ID128="0x279926496a7f5d25da69f2b3b2799a7f"/>
<BS ID128="0x676cb88f302d10227992649885984045"/>
<BS bits="8" string="CID=Toto"/>
<BS ID128="0xccc0f2b3b279926496a7f5d25da692f6"/>
<BS ID128="0xccc0f2b3b279926496a7f5d25da692d6"/>
</DRMInfo>
<CrypTrack trackID="2" IsEncrypted="1" IV_size="16" first_IV="0x0a610676cb88f302d10ac8bc66e039ed" saiSavedBox="senc">
<key KID="0x279926496a7f5d25da69f2b3b2799a7f" value="0xccc0f2b3b279926496a7f5d25da692f6"/>
</CrypTrack>
</GPACDRM>
Well, now i would to decrypt that file with mpeg-dash.
In first, i've created .mpd and segmentated that mp4 file.
.Mpd file looks like following:
<?xml version="1.0"?>
<!-- MPD file Generated with GPAC version 0.6.2-DEV-rev1147-g47f9373-master at 2016-12-03T10:37:20.403Z-->
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" minBufferTime="PT1.500S" type="static" mediaPresentationDuration="PT0H4M30.118S" maxSegmentDuration="PT0H0M3.994S" profiles="urn:mpeg:dash:profile:full:2011" xmlns:cenc="urn:mpeg:cenc:2013">
<ProgramInformation moreInformationURL="http://gpac.io">
<Title>audio-enc.mpd generated by GPAC</Title>
</ProgramInformation>
<Period duration="PT0H4M30.118S">
<AdaptationSet segmentAlignment="true" lang="und">
<ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" cenc:default_KID="27992649-6a7f-5d25-da69-f2b3b2799a7f"/>
<Representation id="1" mimeType="audio/mp4" codecs="mp4a.40.2" audioSamplingRate="44100" startWithSAP="1" bandwidth="103460">
<AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
<SegmentList timescale="44100" duration="176400">
<Initialization sourceURL="segment_audioinit.mp4"/>
<SegmentURL media="segment_audio1.m4s"/>
<SegmentURL media="segment_audio2.m4s"/>
....
<SegmentURL media="segment_audio67.m4s"/>
<SegmentURL media="segment_audio68.m4s"/>
</SegmentList>
</Representation>
</AdaptationSet>
</Period>
</MPD>
Now, this is html of my page:
<!doctype html>
<html>
<head>
<title>Dash.js Rocks</title>
<style>
video {
width: 640px;
height: 360px;
}
</style>
</head>
<body>
<div>
<video id="videoPlayer" controls></video>
</div>
<script src="http://cdn.dashjs.org/latest/dash.all.min.js"></script>
<script src="js/main.js"></script>
<script>
(function(){
var url = "http://localhost:8080/prova-enc/audio-enc.mpd";
var player = dashjs.MediaPlayer().create();
player.initialize(document.querySelector("#videoPlayer"), url, true);
})();
</script>
</body>
</html>
And this is "main.js":
'use strict';
var KEY = new Uint8Array([
0x279926496a7f5d25da69f2b3b2799a7f
]);
var config = [{
initDataTypes: ['mp4'],
videoCapabilities: [{
contentType: 'video/mp4; codecs="mp4a.40.2"'
}]
}];
var video = document.querySelector('videoPlayer');
if(video) {
video.addEventListener('encrypted', handleEncrypted, false);
}
navigator.requestMediaKeySystemAccess('org.w3.clearkey', config).then(
function(keySystemAccess) {
return keySystemAccess.createMediaKeys();
}
).then(
function(createdMediaKeys) {
return video.setMediaKeys(createdMediaKeys);
}
).catch(
function(error) {
console.error('Failed to set up MediaKeys', error);
}
);
function handleEncrypted(event) {
console.log('encrypted event:', event);
var session = video.mediaKeys.createSession();
session.addEventListener('message', handleMessage, false);
session.generateRequest(event.initDataType, event.initData).catch(
function(error) {
console.error('Failed to generate a license request', error);
}
);
}
When i go to my page, on my server, from Chrome (Versione 55.0.2883.75 (64-bit)) this is the output of console:
main.js:29 Failed to set up MediaKeys DOMException: None of the requested configurations were supported.
(anonymous) # main.js:29
Debug.js:108 [23] EME detected on this user agent! (ProtectionModel_21Jan2015)
Debug.js:108 [29] Playback Initialized
Debug.js:108 [49] [dash.js 2.3.0] MediaPlayer has been initialized
XHRLoader.js:223 XHR finished loading: GET "http://localhost:8080/prova-enc/audio-enc.mpd".
c # XHRLoader.js:223
d # XHRLoader.js:256
d # ManifestLoader.js:83
Q # StreamController.js:663
Pb # MediaPlayer.js:1928
Fb # MediaPlayer.js:1772
Db # MediaPlayer.js:1736
b # MediaPlayer.js:169
(anonymous) # dash1.html:23
(anonymous) # dash1.html:24
Debug.js:108 [70] Parsing complete: ( xml2json: 10.3ms, objectiron: 4.63ms, total: 0.0150s)
Debug.js:108 [72] Manifest has been refreshed at Sat Dec 03 2016 16:16:33 GMT+0100 (CET)[1480778193.925]
Debug.js:108 [82] SegmentTimeline detected using calculated Live Edge Time
Debug.js:108 [89] MediaSource attached to element. Waiting on open...
Debug.js:108 [95] MediaSource is open!
Debug.js:108 [96] Duration successfully set to: 270.118
Debug.js:108 [98] Added 0 inline events
Debug.js:108 [98] No video data.
Debug.js:108 [99] audio codec: audio/mp4;codecs="mp4a.40.2"
Debug.js:108 [110] Schedule controller stopping for audio
Debug.js:108 [115] No text data.
Debug.js:108 [115] No fragmentedText data.
Debug.js:108 [116] No embeddedText data.
Debug.js:108 [116] No muxed data.
Debug.js:108 [117] Start Event Controller
Debug.js:108 [120] Schedule controller starting for audio
Debug.js:108 [122] Native video element event: play
XHRLoader.js:223 XHR finished loading: GET "http://localhost:8080/prova-enc/segment_audioinit.mp4".
c # XHRLoader.js:223
d # XHRLoader.js:256
d # FragmentLoader.js:96
n # FragmentModel.js:159
l # FragmentModel.js:150
o # ScheduleController.js:260
d # ScheduleController.js:168
y # ScheduleController.js:303
(anonymous) # EventBus.js:87
c # EventBus.js:87
R # Stream.js:457
Q # Stream.js:437
d # Stream.js:124
b # StreamController.js:427
Debug.js:108 [128] Init fragment finished loading saving to audio's init cache
Debug.js:108 [136] DRM: onNeedKey
Debug.js:108 [136] DRM: initData: /psshy#B«æ[à_
[148] DRM: KeySystem Access Denied! -- Key system access denied!
Can someone helps me? I'm desperate.
Thanks anyway
Your key should be an array of bytes; your line new Uint8Array([0x279926496a7f5d25da69f2b3b2799a7f]) incorrectly creates a single-member array. Instead, you should write it as new Uint8Array([0x27, 0x99, 0x26, 0x49, 0x6a, 0x7f, 0x5d, 0x25, 0xda, 0x69, 0xf2, 0xb3, 0xb2, 0x79, 0x9a, 0x7f]). It then still needs to be encoded to base64 format before use in the JsonWebKey.
Also, you are never generating a license with the key. If you haven't already, please refer to the source of this example page for the correct way to set up a video with ClearKey. Integrate its generateLicense() function into your code (you will also need its toBase64() function to convert your key into the right format). In fact, I would recommend getting that code working on your own machine as-is before writing your own version. Note that it needs to run on a secure context (eg. HTTPS) and, if you want to use their video file, you'll need it to be on the same origin as the app (ie. you will need to host it on your own server).
EDIT: also, the "DOMException: None of the requested configurations were supported." indicates that you may have written your config incorrectly (or specified features that your environment does not support). Unfortunately, I can't help with this because the specification is quite undefined here and I'm struggling with it myself. Again, I suggest getting that minimum working example to run first.

loading a javascript library and not getting an object returned

I am trying to load a javascript library in XPages.
Normally in HTML the reference looks as followed:
<html>
<head>
<script src="https://hammerjs.github.io/dist/hammer.js"></script>
</head>
<body>
</body>
</html>
which gives me a Hammer object in the DOM which I can work further with.
In XPages I have made the following setup:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" disableTheme="true"
dojoForm="false" dojoTheme="false" dojoParseOnLoad="false"
createForm="false">
<xp:this.resources>
<xp:script src="https://hammerjs.github.io/dist/hammer.js"
clientSide="true">
</xp:script>
</xp:this.resources>
</xp:view>
alternatively:
<?xml version="1.0" encoding="UTF-8" ?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" disableTheme="true" dojoForm="false" dojoTheme="false" dojoParseOnLoad="false" createForm="false">
<xp:this.resources>
<xp:headTag tagName="script">
<xp:this.attributes>
<xp:parameter name="script" value="text/javascript" />
<xp:parameter name="src" value="https://hammerjs.github.io/dist/hammer.js" />
</xp:this.attributes>
</xp:headTag>
</xp:this.resources>
</xp:view>
But the Hammer object is not present in the DOM!
What am I doing wrong?
hammer.js uses AMD. Here's a snippet from the hammer.js source code where AMD is used:
if (typeof define == TYPE_FUNCTION && define.amd) {
define(function() {
return Hammer;
});
} else if (typeof module != 'undefined' && module.exports) {
module.exports = Hammer;
} else {
window[exportName] = Hammer;
}
Unfortunately AMD loading conflicts with Dojo in XPages. See this answer on how to remove AMD loading.
In your case you need to download hammer.js, change the AMD loading part, add it to your nsf and then load the script from your nsf instead.
You remove the AMD loading part by changing the code in hammer.js to for instance this:
//if (typeof define == TYPE_FUNCTION && define.amd) {
// define(function() {
// return Hammer;
// });
//} else if (typeof module != 'undefined' && module.exports) {
if (typeof module != 'undefined' && module.exports) {
module.exports = Hammer;
} else {
window[exportName] = Hammer;
}
Another way to handle this is to use the AMD loader which is a part of Dojo on newer versions of Domino.
This code implements the basic example from the hammer.js documentation (I'm only using jQuery for the ready function):
require({
async: true,
aliases: [['jquery', '//code.jquery.com/jquery-1.11.3.min.js'],
['Hammer', '//cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.4/hammer.min.js']]
}, ['jquery', 'Hammer'], function(jq, Hammer){
$(function() {
var myElement = document.getElementById('myElement');
// create a simple instance
// by default, it only adds horizontal recognizers
var mc = new Hammer(myElement);
// listen to events...
mc.on("panleft panright tap press", function(ev) {
myElement.textContent = ev.type +" gesture detected.";
});
});
});
Then just add the code to your xpage in a script tag:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.resources>
<xp:styleSheet href="./css/basicImpl.css"></xp:styleSheet>
<xp:script src="./js/basicImpl.js" clientSide="true"></xp:script>
</xp:this.resources>
<div id="myElement"></div>
</xp:view>
I'm also using the stylesheet from the example:
#myElement {
background: silver;
height: 300px;
text-align: center;
font: 30px/300px Helvetica, Arial, sans-serif;
}
A few things in no particular order:
You can test that the script is loaded by using Chrome Dev Tools, and go to console. You can then put script in to call the hammer code. If the script isn't loaded then you will get an error. Your script might already be loaded.
Verify with the Hammer js site that you are loading the script properly
Try putting your code in the onClientLoad event which just loads client code.
Put the Hammer.js code into your NSF, to make sure you do not have connection issues to github. Use Package Explorer and put the files in the WebContent/js folder. Put any CSS in the WebContent/CSS folder

Play HTML5 Audio Dynamically On Page Load

I know I can use the following in the body to autoplay the sound on page load if embedded in the body, but I wanna try this dynamically.
What I mean by dynamically is to find the audio file, and play onload using JavaScript, or JQuery.
Can anyone help?
<audio preload="auto" tabindex="0" autoplay="true" loop="true">
<source src="shorttones.mp3" type="audio/mpeg" />
<source src="shorttones.ogg" type="audio/ogg" />
Your browser does not support the audio element.
</audio>
I tried this, not working.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="js/buzz.js" type="text/javascript"></script>
<script type="text/javascript">
if (!buzz.isSupported()) {
alert("Your browser does not support the audio element, ogg, or mp3.");
return;
}
buzz.defaults.formats = [ 'ogg', 'mp3' ];
buzz.defaults.preload = 'metadata';
var mySound = new buzz.sound( "sounds/highpitchsound");
mySound.play();
mySound.loop();
</script>
</head>
</html>
If you mean playing without the autoplay, this would be one approach:
<html><body onload="playSound();">
<audio id="noise"></audio>
</body>
<script>
function playSound(){
var snd=document.getElementById('noise');
canPlayMP3 = (typeof snd.canPlayType === "function" && snd.canPlayType("audio/mpeg") !== "");
snd.src=canPlayMP3?'shorttones.mp3':'shorttones.ogg';
snd.load();
snd.play();
}
</script></html>
You might want to take a look at buzz.js: http://buzz.jaysalvat.com/
if (!buzz.isSupported()) {
alert("Your browser does not support the audio element, ogg, or mp3.");
return;
}
var sound = new buzz.sound( "shorttones", {
formats: [ "ogg", "mp3" ]
});
sound.play();

Resources