Is there a way to play background music using Google Apps Script? - audio

I am creating an add-on which would ask the user to select music from a list and it would play it as background music. But previous posts show a sidebar with the user manually pressing the play button. I am wondering if there is a way to play it with Google Apps Script only. Also what would be helpful is if there was a volume property to set the volume?
My Code:
function onOpen(){
DocumentApp.getUi()
.createMenu("Background Music Add-On")
.addItem("Select Music","music")
.addItem("Set Volume","musicVol")
.addToUi();
}
//music selection
function music(){
var musicName = DocumentApp.getUi()
.prompt("Please select one of the music names:\n\nElevator Music,\nLeaf Rag.\nso on...")
switch(musicName){
case "Elevator":
//code to play music Elevator
break;
//So On
}
}

Playing music from a Playlist stored on your Google Drive
This script allows you to store mp3's on your Google Drive. It allows you to select which files you wish to listen too via a playlist. You must start the playlist the first time manually but then the rest of the selections play automatically. The script converts the mp3 files into dataURI's and loads them into the audio element. You can skip over the current selection and you can restart the playlist when it completes.
Code.gs
function onOpen() {
SpreadsheetApp.getUi().createMenu('My Music')
.addItem('Launch Music', 'launchMusicDialog')
.addItem('Create New Music List', 'createMusicList')
.addToUi();
}
function convMediaToDataUri(filename){
var filename=filename || "default.mp3";
var folder=DriveApp.getFolderById("Music Folder Id");
var files=folder.getFilesByName(filename);
var n=0;
while(files.hasNext()) {
var file=files.next();
n++;
}
if(n==1) {
var blob=file.getBlob();
var b64DataUri='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
Logger.log(b64DataUri)
var fObj={filename:file.getName(),uri:b64DataUri}
return fObj;
}
throw("Multiple Files with same name.");
return null;
}
function launchMusicDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('music1');
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Music');
}
function createMusicList() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("MusicList");
var folder=DriveApp.getFolderById("Music Folder Id");
var files=folder.getFiles();
var mA=[['Item','File Name','File Type','File Id','Play List']];
sh.clearContents()
var n=1;
while(files.hasNext()) {
var file=files.next();
mA.push([n++,file.getName(),file.getMimeType(),file.getId(),'']);
}
sh.getRange(1,1,mA.length,mA[0].length).setValues(mA);
sh.getRange(2,2,sh.getLastRow()-1,sh.getLastColumn()-1).sort({column:2,ascending:true});
sh.getRange(2,5,sh.getLastRow()-1,1).insertCheckboxes();
}
function getPlaylist() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('MusicList');
var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
var vA=rg.getValues();
var pl=[];
for(var i=0;i<vA.length;i++) {
if(vA[i][4]) {
pl.push(vA[i][1]);
}
}
return pl;
}
music1.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
label{margin:2px 10px;}
</style>
</head>
<script>
var selectionList=[];
var gVolume=0.2;
var index=0;
$(function(){
document.getElementById('msg').innerHTML="Loading Playlist";
google.script.run
.withSuccessHandler(function(pl){
selectionList=pl;
console.log(pl);
google.script.run
.withSuccessHandler(function(fObj){
$('#audio1').attr('src',fObj.uri);
var audio=document.getElementById("audio1");
audio.volume=gVolume;
audio.onended=function() {
document.getElementById('status').innerHTML='Ended...';
playnext();
}
var msg=document.getElementById('msg');
msg.innerHTML="Click play to begin playlist. Additional selections will begin automatically";
audio.onplay=function() {
document.getElementById('msg').innerHTML='Playing: ' + selectionList[index-1];
document.getElementById('status').innerHTML='Playing...';
document.getElementById('skipbtn').disabled=false;
}
audio.onvolumechange=function(){
gVolume=audio.volume;
}
})
.convMediaToDataUri(selectionList[index++]);
})
.getPlaylist();
});
function playnext() {
if(index<selectionList.length) {
document.getElementById('status').innerHTML='Loading...';
document.getElementById('msg').innerHTML='Next Selection: ' + selectionList[index];
google.script.run
.withSuccessHandler(function(fObj){
$('#audio1').attr('src',fObj.uri);
var audio=document.getElementById('audio1');
audio.volume=gVolume;
audio.play();
})
.convMediaToDataUri(selectionList[index++]);
}else{
document.getElementById('status').innerHTML='Playlist Complete';
document.getElementById('msg').innerHTML='';
document.getElementById('cntrls').innerHTML='<input type="button" value="Replay Playlist" onClick="replayPlaylist()" />';
}
}
function replayPlaylist() {
index=0;
document.getElementById('cntrls').innerHTML='';
playnext();
}
function skip() {
var audio=document.getElementById('audio1');
document.getElementById('skipbtn').disabled=true;
audio.pause();
index++;
playnext();
}
</script>
<body>
<div id="msg"></div>
<audio controls id="audio1" src=""></audio><br />
<div id="status"></div>
<div><input type="button" id="skipbtn" value="Skip" onClick="skip()" disabled /></div>
<div id="cntrls"></div>
</body>
</html>
Please read through the code. You need to add a music folder id and a couple of default.mp3's. The createMusicList() function reads your Music Folder and Loads them into a sheet named 'MusicList' with columns of "Item", "File Name", "File Type" ,"File Id", and PlayList. The last column is just a column of unchecked checkboxes for you to make your current playlist selection. Only one playlist for now, so you can enjoy building your own.
Here's what the dialog looks like:
And here's an image of my MusicList Sheet:
This is where you make your playlist selections.
Audio Properties and Methods
Apps Script Documentation
Latest Script Code

I used the answer to this question as a starting point: playing sound with google script
You would need to open a html sidebar and use an audio tag, to do this you can use the HtmlService class [1].
As a total background you can't, the sidebar must be always open to play the music. But you could still play the audio while editing the document.
To add the audio setting you can add the controls attribute to the audio tag [2]. For playing the audio automatically you can add the autoplay attibute [3].
Here is the code I implemented to achieve your goal. The code gets the selected value and uses it to change the autoplay value to true and to display the audio as well. Also, when the select element is on focus, it gets the previous selected value so later (when a new value is selected) it can be used to stop the previous audio selection and not display it anymore. For these purposes I used the onchange [4] and the onfocus [5] events.
Code.gs
var SIDEBAR_TITLE = 'Sidebar Musicbox';
function onOpen(e) {
DocumentApp.getUi()
.createMenu('Custom Menu')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle(SIDEBAR_TITLE);
DocumentApp.getUi().showSidebar(ui);
}
Sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div class="sidebar branding-below">
<p>
A little music for your enjoyment!
</p>
<form>
<select id="music" onchange="playSelection();" onfocus="setOldValue(this.value);">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<br>
<audio id="player0" controls style="display:none">
<source src="[WEB-URL-FOR-MP3-FILE]" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<audio id="player1" controls style="display:none">
<source src="[WEB-URL-FOR-MP3-FILE]" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<audio id="player2" controls style="display:none">
<source src="[WEB-URL-FOR-MP3-FILE]" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<br>
<div id="sidebar-status"></div>
</div>
<div class="sidebar bottom">
<span class="gray branding-text">Docs Add-on Sound Demo</span>
</div>
</body>
<script>
var previousValue;
//Function called when select onFocus
function setOldValue(e) {
previousValue = e;
}
//Function called when selected value change
function playSelection() {
//Get the value for the selected option
var selectedValue = document.getElementById("music").value;
//Latest and previous selection IDs
var player = "player" + selectedValue;
var previousPlayer = "player" + previousValue;
//Stop and don't display the previous selection of audio
document.getElementById(previousPlayer).style.display = "none";
document.getElementById(previousPlayer).autoplay = false;
document.getElementById(previousPlayer).load();
//Play and display the new selection and put the focus on it
document.getElementById(player).style.display = "block";
document.getElementById(player).autoplay = true;
document.getElementById(player).load();
document.getElementById(player).focus();
}
</script>
</html>
[1] https://developers.google.com/apps-script/guides/html/
[2] https://www.w3schools.com/tags/att_audio_controls.asp
[3] https://www.w3schools.com/tags/att_audio_autoplay.asp
[4] https://www.w3schools.com/jsref/event_onchange.asp
[5] https://www.w3schools.com/jsref/event_onfocus.asp

Related

I have multiple lists on an asp.net webform. I need to show a different popup menu for each list

My form has a Master page, i.e., cannot use a popup Form.
I used the code below to create a popup menu associated with one of the lists, but the popup appears BELOW my list items (I can only see the last two items!) and it appears no matter which list I right click on.
Any help will be appreciated.
Here is my code (modified from a web site example):
<div id="contextMenu" class="context-menu"
style="display: none">
<ul>
<li>New</li>
<li>Edit</li>
<li>View</li>
<li><a href="#">Copy
<li>Refresh</li>
</ul>
</div>
<script type="text/javascript">
document.getElementById('# <% = lstContactsClerk.ClientID %>').oncontextmenu = rightClick;
function rightClick(clickEvent) {
clickEvent.preventDefault();
// return false;
}
</script>
<script>
document.onclick = hideMenu;
document.oncontextmenu = rightClick;
function hideMenu() {
document.getElementById("contextMenu")
.style.display = "none"
}
function rightClick(e) {
e.preventDefault();
if (document.getElementById("contextMenu")
.style.display == "block")
hideMenu();
else {
var menu = document.getElementById("contextMenu")
menu.style.display = 'block';
menu.style.left = e.pageX + "px";
menu.style.top = e.pageY + "px";
}
}
</script>

Changing src attribute for an audio element doesn't work

Changing src attribute for an audio element doesn't work:
var Audio = React.createClass({
render : function() {
return (
<audio src={this.props.data.songUrl}/>
);
}
});
var Music = React.createClass({
render : function() {
return (
<article className="music">
<article className="musicContent">
<MusicButton data={Data} />
<List />
<Footer />
</article>
</article>
);
}
});
var MusicButton = React.createClass({
getInitialState : function() {
return {
isPlay : true,
count : 0
}
},
musicPlay : function () {
var audio = React.findDOMNode(this.refs.audio);
if(this.state.isPlay) {
audio.play();
this.setState({isPlay: false});
} else {
audio.pause();
this.setState({isPlay: true});
}
},
getBackWardMusic : function() {
this.setState({count: ++this.state.count});
var audio = React.findDOMNode(this.refs.audio);
audio.play();
},
getForwardMusic : function() {
this.setState({count: --this.state.count});
var audio = React.findDOMNode(this.refs.audio);
audio.play();
},
render : function() {
var classString = 'iconMusic icon-pause';
if(this.state.isPlay) {
classString = 'iconMusic icon-pause';
} else {
classString += ' rotate';
}
return (
<header className="musicHeader">
<Audio ref="audio" data={this.props.data[this.state.count]} />
<span onClick={this.getBackWardMusic} className="iconMusic icon-backward"></span>
<span onClick={this.musicPlay} className={classString}></span>
<span onClick={this.getForwardMusic} className="iconMusic icon-forward"></span>
</header>
);
}
});
after changing the source of audio you need to .load() first, before play() plays the new source.
you may like to use .oncanplaythroug = .play()
I don't have a specific answer for your question but I've found that media elements have their own lifecycle that I'm not sure is handled correctly in the React wrappers. The React and media element lifecycles have subtle interactions that are difficult to get right.
E.g., in Chrome, media elements don't release their resources unless you set src='' and if you do this in a React class, followed by a src='something-else' then I suspect the src='' can get optimised away.
To manage a video element, for example, I wrapped it in a React component and attached my own event listeners to the video DOM element to help manage its state and also managed cases like src='' and others by directly manipulating the DOM element in componentWillReceiveProps and componentWillUpdate based on what was changing.
Sorry I've not given a complete answer. It would take a lot of time to completely describe everything but I hope this helps a bit.

Dijit.MenuItem and <a href=></a> link

My question is similar to that one:
Dijit Menu (bar) with link
I'm using Dijit Menu as in following listing:
<div data-dojo-type="dijit/Menu">
<div id="menuItem" data-dojo-type="dijit/MenuItem">
urlLink
</div>
</div>
But link is not working as it blocked by dojo.stopEvent in _onClick().
The question is:
How to remove dojo.stopEvent and make link inside <div id="menuItem" data-dojo-type="dijit/MenuItem"> work properly?
The issue:
I need to put inside <div id=menuItem"> some code, which has to receive onClick event.
P.S. Originally this is XPages code.
Well I fell in same problem, saw this post and the related other, but wasn't satisfied with the "onclick" solution :
it didn't work (for me) with keyboard navigation
it imposes to a add script element (onclick=...) in the declarative zone which is not what I expect for unobtrusive JavaScript
Finaly I digged further in dojo and decided to directly use the href attribute of first sub-node in the handler. My script section (derived from dijit menus tutorial) is then :
<script>
require([
"dojo/dom",
"dojo/parser",
"dojo/dom-attr",
"dojo/query",
"dijit/registry",
"dijit/WidgetSet", // for registry.byClass
"dijit/Menu",
"dijit/MenuItem",
"dijit/MenuBar",
"dijit/MenuBarItem",
"dijit/PopupMenuBarItem",
"dojo/domReady!"
], function(dom, parser, domattr, query, registry){
// a menu item selection handler
var onItemSelect = function(event){
dom.byId("lastSelected").innerHTML = this.get("label");
var achild = query("a", this.domNode)[0];
if (achild != null) {
var href = domattr.get(achild, "href");
if ((href != null) && (href != '') && (href != '#')) {
window.location.href = href;
}
}
};
parser.parse();
var setClickHandler = function(item){
item.on("click", onItemSelect);
};
registry.byClass("dijit.MenuItem").forEach(setClickHandler);
registry.byClass("dijit.MenuBarItem").forEach(setClickHandler);
});
</script>
That way I don't have to change anything in a menu of type
<ul><li>...</li></ul>
that works with JavaScript disabled, and links work fine with mouse and keyboard navigation when JavaScript is enabled. Simply don't forget the "class='claro'" in body element ....
What about this:
<div data-dojo-type="dijit/Menu">
<div id="menuItem" data-dojo-type="dijit/MenuItem"
onclick="window.location('http://url.com')">
urlLink
</div>
</div>
Working jsfiddle:
http://jsfiddle.net/KuyYX/

Immediate play sound on button click in HTML page

In my HTML page I have 9 images for dialing numbers and one text box that shows the pressed numbers. I want each of those images to immediately play beep sound when users click on them. I tried to use embed with hidden property and navigate it's source to .wav sound.
It is working OK, but when I press the images one after another immediately, it cannot play sound and just bees once at the end.
Is there any faster way of playing a .wav sound on 'onclick' method?
If you only need to support recent browsers, then HTML 5 offers you the Audio object
to load/buffer your sound:
var snd = new Audio("file.wav");
to play the sound:
snd.play();
to re-cue it to the beginning (so that you can play it again):
snd.currentTime=0;
This answer https://stackoverflow.com/a/7620930/1459653 by #klaustopher (https://stackoverflow.com/users/767272/klaustopher) helped me. He wrote:
HTML5 has the new <audio>-Tag that can be used to play sound. It
even has a pretty simple JavaScript Interface:
<audio id="sound1" src="yoursound.mp3" preload="auto"></audio>
<button onclick="document.getElementById('sound1').play();">Play
it</button>
Here's how I implemented his advice so that clicking on the Font Awesome icon "fa-volume-up" (located on the Web page after "mule.") results in "donkey2.mp3" sound playing (note: mp3 doesn't play in all browsers).
<p>In short, you're treated like a whole person, instead of a rented mule. <audio id="sound1" src="assets/donkey2.mp3" preload="auto"></audio><a class="icon fa-volume-up" onclick="document.getElementById('sound1').play();"></a>
You can use embed element for play sounds, but you've to check the formats supported by the different browsers.
Embed element on MDN
<a onclick="playSound('1.mp3')">
<img src="1.gif">
</a>
<div id="sound"></div>
<script>
var playSound = function (soundFile) {
$("#sound").html("<embed src=\"" + soundFile + "\" hidden=\"true\" autostart=\"true\" />");
}
</script>
This code lets you put in a picture button; when click you get a sound. It works with Google Chrome and Microsoft Edge but I can't get it to work in Internet Explorer. I'm using html 5 codes; please copy and paste and add you own samples.
</head>
<body>
<script>
var audio = new Audio("/Sample.wav ");
audio.oncanplaythrough = function ( ) { }
audio.onended = function ( ) { }
</script> <input type="image" src="file://C:/Sample.jpg" onclick="audio.play ( )">
</body>
</html>
more on codes look at
http://html5doctor.com/html5-audio-the-state-of-play/
Example based on accepted answer (Tested in Chrome 70), but I didn't need to re-cue:
<button onclick="snd.play()"> Click Me </button>
<script>
var snd = new Audio("/Content/mysound.wav");
</script>
This is what I would do to play sound effects:
<html>
<body>
<audio id="sfx"><source src="mysound.mp3"></audio>
<button onclick="playsound()" id="button">Play a sound!</button>
<script> function playsound() {
var sfx = document.getElementById("sfx");
sfx.autoplay = 'true';
sfx.load();}
Or you can run this snippet:
function playsound() {
var mysound = document.getElementById("mysound");
mysound.autoplay = 'true';
mysound.load();
}
button {
color: blue;
border-radius: 24px;
border: 5px solid red;
}
body {
background-color: #bfbfbf;
}
<html>
<body>
<audio id='mysound'><source src="click.mp3"><!-- "click.mp3" isn't a sound effect uploaded to the snippet, because I don't think you can upload sfx to snippets. (I'm new to stackoverflow, so there might be a way) But if you actually use a sound effect in that folder that you're using, it works. --></audio>
<button id='btn' onclick='playsound()'>Play a sound!</button>
</body>
</html>

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