Advertisement
ChrisPrunotto

Java + HTML - Simple Audio Sprite

Jul 31st, 2013
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //THIS GOES IN YOUR JAVASCRIPT FILE.
  2. //Create the audiosprite.
  3. var audioSprite = document.getElementById('audio');
  4.  
  5. // the locations of each sound effect, in seconds.
  6. var spriteData = {
  7.     silence: {
  8.         start: 0,
  9.         length: 1.9
  10.     },
  11.     BookSlide: {
  12.         start: 2,
  13.         length: .9
  14.     },
  15.     BookSlam: {
  16.         start: 3,
  17.         length: .9
  18.     },
  19.     BookOnDesk: {
  20.         start: 4,
  21.         length: .9
  22.     }
  23.     PagesTurned: {
  24.     start: 5,
  25.     length: .9
  26.     }
  27.     ButtonSound: {
  28.     start: 6,
  29.     length: .9
  30.     }
  31. };
  32.  
  33. // current sprite being played
  34. var currentSprite = {};
  35.  
  36. // time updater to ensure that the audio is stopped when a sprite is complete
  37. var onTimeUpdate = function() {
  38.     if (this.currentTime >= currentSprite.start + currentSprite.length) {
  39.         this.pause();
  40.     }
  41. };
  42. //audio listener event.
  43. audioSprite.addEventListener('timeupdate', onTimeUpdate, false);
  44.  
  45. // load the audio.
  46.  
  47. var playSprite = function(id) {
  48.     if (spriteData[id] && spriteData[id].length) {
  49.         currentSprite = spriteData[id];
  50.         audioSprite.currentTime = currentSprite.start;
  51.         audioSprite.play();
  52.     }
  53.  
  54. //THIS GOES WHEREVER YOU WANT IT TO GO IN YOUR HTML FILE.
  55. <audio id="audio">
  56.     <source src="(THE NAME AND LOCATION OF YOUR AUDIO SPRITE).m4a" type="audio/mpeg" /> <!--https://soundcloud.com/chris_bob/audio-sprite-example-output is the one used int his file-->
  57.     <source src="http://exampleaudiospritesheet.something.com/booksounds.ogg" type="audio/ogg" />
  58. </audio>
  59. <button onclick="playSprite('BookSlide');">Slide the Book Around</button>
  60. <button onclick="playSprite('BookSlam');">Slam the Book Shut</button>
  61. <button onclick="playSprite('BookOnDesk');">Slam the Book on the Desk</button>
  62. <button onclick="playSprite('PagesTurned');">Turn the Pages</button>
  63. <button onclick="playSprite('ButtonSound');">Play A Button Sound</button>
  64.  
  65. <!--www.chrisprunotto.com ; www.chrisprunotto.wordpress.com -->
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement