有没有一种方法可以使用Google Apps脚本播放背景音乐?

时间:2019-09-12 21:50:53

标签: audio google-apps-script

我正在创建一个插件,要求用户从列表中选择音乐,并将其作为背景音乐播放。但是以前的帖子显示了侧边栏,用户手动按下了播放按钮。我想知道是否有一种方法只能通过Google Apps脚本播放。另外,如果有用于设置音量的音量属性,那会有所帮助吗?
我的代码:

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
     }
}

2 个答案:

答案 0 :(得分:1)

播放存储在Google云端硬盘中的播放列表中的音乐

此脚本允许您将mp3存储在Google云端硬盘上。它允许您通过播放列表选择想要收听的文件。您必须第一次手动启动播放列表,但随后的其他选择会自动播放。该脚本将mp3文件转换为dataURI,并将其加载到音频元素中。您可以跳过当前选择,并在播放列表完成后重新开始播放。

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>
  

请仔细阅读代码。您需要添加一个音乐文件夹ID和几个default.mp3。 createMusicList()函数读取您的音乐文件夹,并将其加载到名为“ MusicList”的工作表中,该工作表的列为“项目”,“文件名”,“文件类型”,“文件ID”和“播放列表”。最后一列只是未选中复选框的一列,供您选择当前的播放列表。目前只有一个播放列表,因此您可以建立自己的播放列表。

这是对话框的样子:

enter image description here

这是我的MusicList工作表的图片:

enter image description here

在这里您可以选择播放列表。

Audio Properties and Methods

Apps Script Documentation

Latest Script Code

答案 1 :(得分:0)

我以这个问题的答案作为起点:playing sound with google script

您需要打开html边栏并使用音频标签,为此,您可以使用HtmlService类[1]。

作为总背景,侧栏必须始终打开才能播放音乐。但是您仍然可以在编辑文档时播放音频。

要添加音频设置,可以将controls属性添加到音频标签[2]。要自动播放音频,您可以添加autoplay头像[3]。

这是我为实现您的目标而实施的代码。该代码获取选定的值,并使用该值将autoplay值更改为true并显示音频。同样,当select元素处于焦点位置时,它将获得先前选择的值,因此稍后(当选择新值时)它可以用于停止先前的音频选择并且不再显示。为此,我使用了onchange [4]和onfocus [5]事件。

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