Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

HTML

            
              <h1 class="well text-center well-sm">Voice-Controlled Audio Player</h1>

<div class="col-md-12 context">
  <p class="big">Contextual</p>
  <p> Last Command: <span class="l-command"></span></p>
  <p>Status: <span class="status"></span> </p>
</div>

<div class="col-md-5">
  <p class="big text-center"><span class="glyphicon glyphicon-info-sign"></span> Available Commands:</p>
  <ul class="list-group">
    <li class="list-group-item list-group-item-success"><strong>Play</strong> - Plays the current song or starts the first song.</li>
    <li class="list-group-item list-group-item-success"><strong>Stop</strong> - Stops the the current song and nullifies the playback time.</li>
    <li class="list-group-item list-group-item-success"><strong>Pause</strong> - Pauses the current song.</li>
    <li class="list-group-item list-group-item-success"><strong>Next</strong> Plays the next song in the list.</li>
    <li class="list-group-item list-group-item-success"><strong>Previous</strong> - Plays the previous song in the list. </li>
    <li class="list-group-item list-group-item-success"><strong>Play &lt;slice from song's or singer's name&gt;</strong> - Plays a song with a particular name, if found.</li>
    <li class="list-group-item list-group-item-warning">The songs are taken from <a href="http://freemusicarchive.org/" target="_blank">http://freemusicarchive.org/</a> and the spinner icon from
      <a target="_blank" href="http://www.wikimedia.org">Wikimedia</a></li>
  </ul>
</div>

<div class="col-md-6">
  <p class="lead text-center">We offer you the following amazing songs:</p>
  <ul class="list-group" id="playlist"></ul>
</div>

<div id="spinner">
  <img src="http://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif" alt="Loading">
</div>
            
          
!

CSS

            
              #spinner {
  display: none;
  position: fixed;
  z-index: 111;
  left: 50%;
  top: 80%;
}

.glyphicon-headphones {
  color: crimson;
  font-size: 1.3em;
  margin-left: 5px;
}

.big {
  font-size: 1.5em;
  font-weight: bolder;
}

.context{
  margin-bottom: 10px;
}
            
          
!

JS

            
              var data = {
  "songs": [
    {
      "fileName": "https://www.ruse-problem.org/songs/RunningWaters.mp3",
      "singer": "Jason Shaw",
      "songName": "Running Waters"
    },
    {
      "fileName": "https://www.ruse-problem.org/songs/Enthusiast.mp3",
      "singer": "Tours",
      "songName": "Enthusiast"
    },
    {
      "fileName": "https://www.ruse-problem.org/songs/SkyRide.mp3",
      "singer": "Itasca",
      "songName": "Sky Ride"
    },
    {
      "fileName": "https://www.ruse-problem.org/songs/Starling.mp3",
      "singer": "Podington Bear",
      "songName": "Starling"
    },
    {
      "fileName": "https://www.ruse-problem.org/songs/HachikoTheFaithtfulDog.mp3",
      "singer": "The Kyoto Connection",
      "songName": "Hachiko The Faithful Dog"
    },
    {
      "fileName": "https://www.ruse-problem.org/songs/FaterLee.mp3",
      "singer": "Black Ant",
      "songName": "Father Lee"
    },
    {
      "fileName": "https://www.ruse-problem.org/songs/EpicSong.mp3",
      "singer": "BoxCat Games",
      "songName": "Epic Song"
    }
  ]
};

var audioPlayer = {
  audioData: {
    currentSong: -1,
    songs: []
  },

  // UI
  load: function() {
    this.data = data.songs;
    data.songs.forEach(function(val, i) {
      $("#playlist").append(
        "<li class='list-group-item'>" + val.singer + " - " + val.songName
      );
    })
  },
  changeCurrentSongEffect: function(options) {
    if (options.play) {
      $("#playlist .list-group-item")
        .removeClass("list-group-item-success").find("span").remove();
      $("#playlist .list-group-item")
        .eq(this.audioData.currentSong)
        .addClass("list-group-item-success")
        .removeClass("list-group-item-danger")
        .append("<span class='glyphicon glyphicon-headphones'>");
    }
    if (options.end) {
      $("#playlist .list-group-item")
      .eq(this.audioData.currentSong)
      .removeClass("list-group-item-success glyphicon-headphones")
      .addClass("list-group-item-danger");
    }
  },
  playSong: function(audio) {
    this.changeCurrentSongEffect({
      play: 1
    });
    audio.onended = function() {
      audioPlayer.changeCurrentSongEffect({
        end: 1
      });
      audioPlayer.changeStatusCode("Finished listening to", true);
    }
    this.changeStatusCode("Playing", true, audio);
  },
  changeStatusCode: function(statusMessage, addSongName, scope) {
    if (addSongName) {
      statusMessage += " " + $("#playlist .list-group-item").eq(this.audioData.currentSong).text();
    }
    this.speak(statusMessage, scope);
    $(".status")
    .fadeOut("slow")
    .html(statusMessage)
    .fadeIn("slow");
  },
  changeLastCommand: function(cmd) {
    $(".l-command").fadeOut("slow")
    .text(cmd)
    .fadeIn("slow");
  },
  toggleSpinner: function(show) {
    (show || false) ? $("#spinner").fadeIn(900) : $("#spinner").fadeOut(1200);
  },

  // Audio Player
  play: function() {
    var currentSong = this.audioData.currentSong;
    if (currentSong === -1) {
      this.audioData.currentSong = ++currentSong;
      this.audioData.songs[this.audioData.currentSong] = new Audio(
        this.data[0].fileName);
      this.playSong(this.audioData.songs[currentSong]);

    } else {
      this.playSong(this.audioData.songs[currentSong]);
    }
  },
  pauseSong: function(audio, stopPlayback) {
    if (audio.paused) {
      return;
    }
    audio.pause();
    if (stopPlayback) {
      this.changeStatusCode("Stopped", true);
      audio.currentTime = 0;
      return;
    }
    this.changeStatusCode("Paused", true);
  },
  stop: function(stopPlayback) {
    this.pauseSong(this.audioData.songs[this.audioData.currentSong], stopPlayback || false);
    if (stopPlayback) {
      this.audioData.songs[this.audioData.currentSong].currentTime = 0;
    }
  },
  prev: function() {
    var currentSong = this.audioData.currentSong;
    if (typeof this.audioData.songs[currentSong - 1] !== 'undefined') {
      this.pauseSong(this.audioData.songs[currentSong]);
      this.audioData.currentSong = --currentSong;
      this.playSong(this.audioData.songs[currentSong]);

    } else if (currentSong > 0) {
      this.pauseSong(this.audioData.songs[currentSong]);
      this.audioData.currentSong = currentSong = --currentSong;
      this.audioData.songs[this.audioData.currentSong] = new Audio(
        this.data[currentSong].fileName);
      this.playSong(this.audioData.songs[currentSong]);
    } else {
      this.changeStatusCode("There are no previous songs.");
    }
  },
  next: function() {
    var currentSong = this.audioData.currentSong;
    if (currentSong > -1) {
      this.pauseSong(this.audioData.songs[currentSong]);
    }
    if (typeof this.data[currentSong + 1] !== 'undefined') {
      currentSong = ++this.audioData.currentSong;
      this.audioData.songs[this.audioData.currentSong] = new Audio(this.data[currentSong].fileName);
      this.playSong(this.audioData.songs[currentSong]);
    } else {
      this.changeStatusCode("You have reached the final song.");
    }
  },
  searchSpecificSong: function(keyword) {
    try {
      this.data.forEach(function(val, i) {
        if (val.songName.trim().toLowerCase().indexOf(keyword) !== -1 ||
            val.singer.trim().toLowerCase().indexOf(keyword) !== -1) {
          if (typeof this.audioData.songs[i] !== 'undefined') {
            //if the song is already cached
            if (this.audioData.currentSong > -1) {
              this.pauseSong(this.audioData.songs[this.audioData.currentSong]);
            }
            this.audioData.currentSong = i;
            audioPlayer.playSong(audioPlayer.audioData.songs[i]);
            throw LoopBreakException;
          } else {
            //add the song and play it
            if (this.audioData.currentSong > -1) {
              this.pauseSong(this.audioData.songs[this.audioData.currentSong]);
            }
            this.audioData.currentSong = i;
            this.audioData.songs[i] = new Audio(this.data[i].fileName);
            this.playSong(this.audioData.songs[i]);
            throw LoopBreakException;
          }
        }
      }, audioPlayer);
    } catch (e) {
      return e;
    }
  },

  // Speech API
  speak: function(text, scope) {
    var message = new SpeechSynthesisUtterance(text.replace("-", " "));
    message.rate = 1;
    window.speechSynthesis.speak(message);
    if (scope) {
      message.onend = function() {
        scope.play();
      }
    }
  },
  processCommands: function(cmd) {
    this.changeLastCommand(cmd);
    var playSpecific = cmd.match(/play\s*(.+)$/);
    if (playSpecific) {
      this.searchSpecificSong(playSpecific[1]);
      return;
    }
    switch (cmd) {
      case "play":
        this.play();
        break;
      case 'pause':
        this.stop();
        break;
      case "stop":
        this.stop(true);
        break;
      case "next":
        this.next();
        break;
      case "previous":
        this.prev();
        break;
      default:
        this.speak("Your command was invalid!", false);
    }
  },
}

$(function() {
  audioPlayer.load();
  if (window['webkitSpeechRecognition']) {
    var speechRecognizer = new webkitSpeechRecognition();
    // recognition will not end when user stops speaking if set to true
    speechRecognizer.continuous = true;
    // process the request while the user is speaking
    // and their commands are final. Set to false by default
    speechRecognizer.interimResults = true;
    speechRecognizer.lang = "en-US";
    var currentCommands = ['play', 'stop', 'pause', 'next', 'previous'],
        results = [],
        timeoutSet = false;

    speechRecognizer.onresult = function (evt) {
      audioPlayer.toggleSpinner(true);
      results.push(evt.results);
      if (!timeoutSet) {
        setTimeout(function() {
          timeoutSet = false;
          results.reverse();
          try {
            results.forEach(function (val, i) {
              var el = val[0][0].transcript.toLowerCase();
              if (currentCommands.indexOf(el.split(" ")[0]) !== -1) {
                speechRecognizer.abort();
                audioPlayer.processCommands(el);
                audioPlayer.toggleSpinner();
                results = [];
                throw new BreakLoopException;
              }
              if (i === 0) {
                audioPlayer.processCommands(el);
                speechRecognizer.abort();
                audioPlayer.toggleSpinner();
                results = [];
              }
            });
          }
          catch(e) {return e;}
        }, 3000)
      }
      timeoutSet = true;
    }
    speechRecognizer.onend = function () {
      speechRecognizer.start();
    }
    speechRecognizer.start();
  }
  else {
    alert("Your browser does not support the Web Speech API");
  }
});

            
          
!
999px

Console