MagicMirror Forum
    • Recent
    • Tags
    • Unsolved
    • Solved
    • MagicMirror² Repository
    • Documentation
    • 3rd-Party-Modules
    • Donate
    • Discord
    • Register
    • Login
    1. Home
    2. bachoo786
    3. Posts
    A New Chapter for MagicMirror: The Community Takes the Lead
    Read the statement by Michael Teeuw here.
    B
    Offline
    • Profile
    • Following 0
    • Followers 0
    • Topics 3
    • Posts 119
    • Groups 0

    Posts

    Recent Best Controversial
    • RE: MP3 Player

      @sdetweil said in MP3 Player:

      @bachoo786 said in MP3 Player:

      fs.readdir(musicFolder, (err, files) => {

      the modulename.js that runs in the browser cannot read files directly, due to security restrictions ( any script could read ALL your files without you knowing)

      this is why the node_helper exists…

      so whats the alternative? I had this MMM-QuranPlayer module that was able to read mp3 files from the folders in the “public” directory which was located in the root folder of the module.

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @bachoo786

      I changed from this:

      if (MP3.config.musicData) {
              const musicList = MP3.createElement("ul", "musicList", "musicList");
      
              MP3.config.musicData.forEach(folderData => {
                  // Folder item
                  const folderItem = MP3.createElement("li", "folderItem", `folderItem-${folderData.folderName}`);
                  folderItem.innerHTML = `
                      <span class="folderName">${folderData.folderName}</span>
                      <i class="fa fa-chevron-down"></i> 
                  `; 
      
                  // Songs list within the folder
                  const songsList = MP3.createElement("ul", "songsList", `songsList-${folderData.folderName}`);
                  songsList.style.display = 'none'; // Initially hide the songs list
      
                  folderData.songs.forEach(song => {
                      const songItem = MP3.createElement("li", "songItem", `songItem-${song}`);
                      songItem.innerHTML = song.substr(0, song.length - 4); 
                      songsList.appendChild(songItem);
                  });
      
                  // Click event listeners
                  folderItem.addEventListener('click', () => {
                      songsList.style.display = songsList.style.display === 'none' ? 'block' : 'none'; // Toggle display
                      folderItem.querySelector('.fa').classList.toggle('fa-chevron-down');
                      folderItem.querySelector('.fa').classList.toggle('fa-chevron-up');
                  });
      
                  songsList.addEventListener('click', (event) => {
                      const clickedSongItem = event.target;
                      if (clickedSongItem.classList.contains('songItem')) {
                          const songName = clickedSongItem.innerText;
                          const folderName = folderData.folderName;
                          MP3.playSong(folderName, songName);
                      }
                  });
      
                  folderItem.appendChild(songsList);
                  musicList.appendChild(folderItem);
              });
      

      to this:

      if (MP3.config.musicData) {
         const fs = require('fs');
         const path = require('path');
      
         const musicFolder = path.resolve(MP3.config.musicData.musicPath);
         const supportedExtensions = this.defaults.extensions; // Use module's default extensions
      
         fs.readdir(musicFolder, (err, files) => {
          if (err) {
           console.error("Error reading music directory:", err);
           // Handle the error - display message to user, etc. 
          } else {
           const musicFiles = files.filter(file => supportedExtensions.includes(path.extname(file).toLowerCase()));
      
           if (musicFiles.length > 0) {
            const musicList = MP3.createElement("ul", "musicList");
      
            musicFiles.forEach(musicFile => {
             const songItem = MP3.createElement('li', 'songItem');
             songItem.innerHTML = musicFile.substr(0, musicFile.length - 4); 
             songItem.addEventListener('click', () => {
              MP3.playSong(musicFile); // Assuming you want to play the song directly
             });
             musicList.appendChild(songItem);
            });
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil so I made a mistake, i wanted my code to look for the mp3 files automatically in the folders within the music directory.

      currently I am getting an error in the developer console:

      Uncaught SyntaxError: Unexpected token ',' (at MMM-MP3Player.js:184:2)
      

      its the “,” at the end of

      return wrapper
      

      I am trying to have one ‘music’ folder with subfolders for each artist containing their songs. This way, the module would display artists on the frontend, and clicking an artist’s name would show the songs in their folder, and click on the song would then play the mp3 file.

      feel like giving up really even though I think I am close

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil here is the repo:

      https://github.com/bachoo786/MMM-MP3Player

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil I will .

      Nothing says everything is loaded including the mp3 player module.

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil sorry to mess with your head but I have been working on this for the last 3 hours and have come up with the following that should show the folders on the front end and when any folder is clicked it should reveal the mp3 files. the issue I am facing is that I am having no errors whatsoever but the module will just not show on the front end. I am pulling my hair out now !

      these are my files:

      node_helper.js:

      var NodeHelper = require('node_helper');
      const Fs = require('fs');
      
      module.exports = NodeHelper.create({
          start: function() {
              console.log("Loaded MP3Player node_helper");
          },
      
          socketNotificationReceived: function(notification, payload) {
              var self = this;
              if (notification === 'SOURCE_MUSIC') {
                  const musicPath = payload.musicPath;
                  const extensions = payload.extensions;
      
                  Fs.readdir(musicPath, (err, folders) => {
                      if (err) {
                          console.error("Error reading music directory:", err);
                          self.sendSocketNotification('ERROR', {message: "Error reading music directory"});
                      } else {
                          const musicData = folders.map(folder => ({
                              folderName: folder,
                              songs: Fs.readdirSync(`${musicPath}/${folder}`).filter(file => self.checkExt(file, extensions))
                          }));
                          self.sendSocketNotification("RETURNED_MUSIC", { musicData: musicData }); 
                      }
                  });
              }
          },
      
          checkExt: function(file, ext) {
              return ext.some(extension => file.toLowerCase().endsWith(extension)); 
          }
      });
      

      MMM-MP3Player.js:

      var MP3;
      var substr;
      Module.register("MMM-MP3Player", {
        defaults: {
          songs: [],
          musicPath: "modules/MMM-MP3Player/music",
          extensions: ["mp3", "wma", "acc", "ogg"],
          songs: null,
          autoPlay: false,
          random: false,
        },
        audio: null,
        songTitle: null,
        mediaPlayer: null,
        dataAvailable: true,
        curSong :0,
        curLength : 0,
        time: null,
        play: null,
        firstTime: true,
        substr: null,
        
        getStyles: function(){
          return ["MMM-MP3Player.css", "font-awesome.css"];
        },
      
        start: function(){
          MP3 = this;
          console.log("autoPlay configuration:", MP3.config.autoPlay);
          Log.info("Starting module: " + MP3.name);
        },
      
      getDom: function() {
          var wrapper = document.createElement("div");
      
          if (MP3.config.musicData) {
              const musicList = MP3.createElement("ul", "musicList", "musicList");
      
              MP3.config.musicData.forEach(folderData => {
                  // Folder item
                  const folderItem = MP3.createElement("li", "folderItem", `folderItem-${folderData.folderName}`);
                  folderItem.innerHTML = `
                      <span class="folderName">${folderData.folderName}</span>
                      <i class="fa fa-chevron-down"></i> 
                  `; 
      
                  // Songs list within the folder
                  const songsList = MP3.createElement("ul", "songsList", `songsList-${folderData.folderName}`);
                  songsList.style.display = 'none'; // Initially hide the songs list
      
                  folderData.songs.forEach(song => {
                      const songItem = MP3.createElement("li", "songItem", `songItem-${song}`);
                      songItem.innerHTML = song.substr(0, song.length - 4); 
                      songsList.appendChild(songItem);
                  });
      
                  // Click event listeners
                  folderItem.addEventListener('click', () => {
                      songsList.style.display = songsList.style.display === 'none' ? 'block' : 'none'; // Toggle display
                      folderItem.querySelector('.fa').classList.toggle('fa-chevron-down');
                      folderItem.querySelector('.fa').classList.toggle('fa-chevron-up');
                  });
      
                  songsList.addEventListener('click', (event) => {
                      const clickedSongItem = event.target;
                      if (clickedSongItem.classList.contains('songItem')) {
                          const songName = clickedSongItem.innerText;
                          const folderName = folderData.folderName;
                          MP3.playSong(folderName, songName);
                      }
                  });
      
                  folderItem.appendChild(songsList);
                  musicList.appendChild(folderItem);
              });
      
              wrapper.appendChild(musicList); 
      
              // Add the rest of the existing code...
              MP3.mediaPlayer = MP3.createElement("div", "mediaPlayer", "mediaPlayer");
              MP3.audio = MP3.createElement("audio", "audioPlayer", "audioPlayer");
              MP3.audio.addEventListener("loadeddata", () => {
                  MP3.dataAvailable = true;
                  MP3.curLength = MP3.audio.duration;
                  MP3.updateDurationLabel(); 
              }),
              MP3.audio.addEventListener("ended", () => {
                  Log.log(" play ended")
                  MP3.audio.currentTime = 0;
                  if(MP3.config.autoPlay)
                  {
                      MP3.loadNext(MP3.config.random)
                  }
                  else
                      MP3.mediaPlayer.classList.toggle("play");
              }),
      
      MP3.audio.addEventListener("timeupdate", () => {
        MP3.updateDurationLabel();
      }),
              MP3.mediaPlayer.appendChild(MP3.audio);
      
              // Add the rest of the controls to MP3.mediaPlayer
              var controls = MP3.createElement("div", "controls", false);
              MP3.songTitle = MP3.createElement("span", "title", "songTitle");
              MP3.setCurrentSong(MP3.curSong);
              controls.appendChild(MP3.songTitle);
      
              var discArea = MP3.createElement("div", "discarea", false);
              discArea.appendChild(MP3.createElement("div", "disc", false));
              var stylus = MP3.createElement("div", "stylus", false);
              stylus.appendChild(MP3.createElement("div", "pivot", false));
              stylus.appendChild(MP3.createElement("div", "arm", false));
              stylus.appendChild(MP3.createElement("div", "head", false));
              discArea.appendChild(stylus);
              MP3.mediaPlayer.appendChild(discArea);
      
            var buttons = MP3.createElement("div", "buttons", false);
      
            //  Previous Button
            var prev = MP3.createButton("back", "prevButton", "fa fa-backward");
            prev.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.audio.play();
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
            }, false),
            buttons.appendChild(prev);
      
            //  Play Button
            MP3.play = MP3.createButton("play", "playButton", "fa fa-play");
            MP3.play.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              if (MP3.audio.paused) {
                setTimeout(() => {
                  MP3.audio.play();
                }, 300);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                MP3.timer = setInterval(MP3.updateDurationLabel, 100);
              } else {
                //MP3.loadNext(MP3.config.random);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
                clearInterval(MP3.timer);
                MP3.audio.pause();
              }
            }, false);
            buttons.appendChild(MP3.play);
      
            //  Stop Button
            var stop = MP3.createButton("stop", "stopButton", "fa fa-stop");
            stop.addEventListener("click", () => {
              MP3.mediaPlayer.classList.remove("play");
              MP3.audio.pause();
              MP3.audio.currentTime = 0;
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
              MP3.updateDurationLabel();
            }, false);
            buttons.appendChild(stop);
      
            //  Next Button
            var next = MP3.createButton("next", "nextButton", "fa fa-forward");
            next.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
            }, false);
            buttons.appendChild(next);
      
              controls.appendChild(buttons);
      
              var subControls = MP3.createElement("div", "subControls", false);
              var duration = MP3.createElement("span", "duration", "currentDuration");
              duration.innerHTML = "00:00" + "&nbsp&nbsp&nbsp";
              subControls.appendChild(duration);
      
              var volumeSlider = MP3.createElement("input", "volumeSlider", "volumeSlider");
              volumeSlider.type = "range";
              volumeSlider.min = "0";
              volumeSlider.max = "1";
              volumeSlider.step = "0.01";
              volumeSlider.addEventListener("input", () => {
                  MP3.audio.volume = parseFloat(volumeSlider.value);
              }, false);
      
              subControls.appendChild(volumeSlider);
              controls.appendChild(subControls);
              MP3.mediaPlayer.appendChild(controls);
      
              wrapper.appendChild(MP3.mediaPlayer);
          }
      
          if(MP3.firstTime && MP3.config.autoPlay){
              console.log("First time and autoPlay are true. Setting firstTime to false.");
              MP3.firstTime=false;
          }
          return wrapper;
      },
      
      playSong: function(folderName, songName) {
          const songPath = MP3.config.musicPath + '/' + folderName + '/' + songName;
          MP3.audio.src = songPath; 
          MP3.songTitle.innerHTML = songName;
          MP3.audio.play();
      },
      
        createElement: function(type, className, id){
          var elem = document.createElement(type);
          if(className) elem.className = className;
          if(id)  elem.id = id;
          return elem;
        },
      
        createButton: function(className, id, icon){
          var button = document.createElement('button');
          button.className = className;
          button.id = id;
          var ico = document.createElement("i");
          ico.className = icon;
          button.appendChild(ico);
          return button;
        },
      
      updateDurationLabel: function() {
        var duration = document.getElementById('currentDuration');
        if (MP3.dataAvailable && MP3.audio.duration > 0) {
          duration.innerText = MP3.parseTime(MP3.audio.currentTime) + " / " + MP3.parseTime(MP3.audio.duration);
        } else {
          duration.innerText = "00:00 / 00:00";
        }
      },
      
        parseTime: function(time){
          const minutes = Math.floor(time / 60)
          const seconds = Math.floor(time - minutes * 60)
          const secondsZero = seconds < 10 ? "0" : ""
          const minutesZero = minutes < 10 ? "0" : ""
          return minutesZero + minutes.toString() + ":" + secondsZero + seconds.toString()
        },
        
        setCurrentSong: function(index){
            if(MP3.audio!= undefined){
              MP3.audio.src = MP3.config.musicPath + '/' + MP3.config.songs[index];
              MP3.songTitle.innerHTML = MP3.config.songs[index].substr(0, MP3.config.songs[index].length - 4);
              MP3.curSong = index;
            }
        },
        loadNext: function(next){
         let index=0;
            console.log("loadNext: Autoplay:", MP3.config.autoPlay); // Add this line for logging
            MP3.audio.pause();
            if(next)  index= (MP3.curSong + 1) % MP3.config.songs.length;
            else      index = (MP3.curSong - 1) < 0 ? MP3.config.songs.length - 1 : MP3.curSong - 1;
            MP3.setCurrentSong(index);
            MP3.audio.play();
        },
      
        notificationReceived: function (notification, payload) {
          if(notification === "ALL_MODULES_STARTED")
      		  MP3.sendSocketNotification('SOURCE_MUSIC', MP3.config);
        },
        
        socketNotificationReceived: function(notification, payload){
          if(notification === "RETURNED_MUSIC")
            MP3.config.songs = payload.songs;
            // set the initial song index 
            MP3.setCurrentSong(0);
            // paint the player
            MP3.updateDom(2);
        },
      });
      

      MMM-MP3Player.css:

      @import url("https://fonts.googleapis.com/css?family=Roboto"); /* Simpler, modern font */
      
      
      .MMM-MP3Player .songInfo {
          flex: 1; /* Fill half of the available space */
          padding: 20px;
          font-family: 'Roboto', sans-serif;
      }
      
      .MMM-MP3Player .songTitle {
          font-size: 4em;
          font-weight: bold;
          color: #333; /* Darker text */
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
      }
      
      .MMM-MP3Player .container {
          position: relative; /* Add this if not present */
          /* ...other styles... */
      }
      
      .MMM-MP3Player .songsList {
          position: absolute;
          left: 10px; /* Adjust to align correctly, can be in px or % */
          top: -360px;  /* Adjust to align correctly, can be in px or % */
          width: 50%; /* Adjust to not exceed the container width */
          max-width: calc(100% - 40px); /* Subtract total horizontal padding */
          align-items: center;
          padding: 20px;
          box-sizing: border-box;
          font-size: 2em;
          font-weight: bold;
          color: #FFF;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          z-index: 1000;
          background-image: 
              linear-gradient(
                  to bottom,
                  rgba(255, 255, 255, 0.8) 0%, 
                  rgba(255, 255, 255, 0.75) 25%, 
                  rgba(255, 255, 255, 0.6) 50%,
                  rgba(255, 255, 255, 0.4) 75%,
                  rgba(255, 255, 255, 0.3) 100%
              ),
              url('images/qsonglist.png');
          background-size: cover;
          background-position: center;    border-radius: 20px;
          border: 1px solid rgba(255, 255, 255, 0.3);
          backdrop-filter: blur(15px);
          -webkit-backdrop-filter: blur(15px);
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
      }
      
      .MMM-MP3Player .mediaPlayer {
          position: absolute;
          right: 0;  /* Adjust as needed to align to the right */
          top: -130px;       /* Aligns to the top of the container */
          width: 50%;   /* Or whatever width you require */
          align-items: center;
          padding: 20px;
          box-sizing: border-box;
          justify-content: center;
          z-index: 1000; 
      }
      
      
      .MMM-MP3Player .controls {
          width: 80%;
          margin-top: 20px; 
      }
      
      .MMM-MP3Player .buttons button {
          background-color: #4CAF50; /* Example: Green for modern feel */
          color: white;
          border: none;
          border-radius: 50%;
          margin-right: 10px; 
          font-size: 1.2em;
          width: 50px;
          height: 50px;
          box-shadow: 0 2px 5px rgba(0,0,0,0.3); /* Adds depth */
      }
      
      .MMM-MP3Player .buttons button:hover {
          background-color: #3e8e41; /* Darker green on hover */
          cursor: pointer;
      }
      

      in my config.js:

      I have added it this way:

      {
          module: "MMM-MP3Player",
          position: "bottom_center",
          "pages": {"Audio": "bottom_center"},
      			config: {
      				musicPath: "modules/MMM-MP3Player/music", 
      				autoPlay: false,
      				random: false,
      				loopList: false,
      			}
      },
      

      Can you tell me what am I doing wrong? thanks

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil ok I will try and explain the “better” method:

      I’m basically trying to add a playlist feature to the MP3 player module I’m working on. My initial setup involved adding a songList to MP3Player.js, which lists all the songs—.mp3 files—in the ‘music’ folder of the module. I’ve also added a second folder, ‘music2’, to categorize songs by artist. Each artist’s name is tagged with an ‘h2’ in the CSS, for both songList and songList2.

      However, this setup becomes cumbersome because it requires repeating the process for multiple artists, creating many folders and modifying the code each time for songList3, songList4, etc.

      I thought a better approach would be to have one ‘music’ folder with subfolders for each artist containing their songs. This way, the module would display artists on the frontend, and clicking an artist’s name would show the songs in their folder.

      I did start on this more streamlined method, but it proved challenging, so I reverted to the simpler, original method which we’ve been discussing since yesterday, as that uses a “single” songList displaying songs from the ‘music’ folder and has been working for me. So I have been trying to add another “songList2” to add more artists and their respective music.

      I hope that makes sense?

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil ah right so I need to change it to something like this:

      MP3.setCurrentSong(0, 'songName');
      

      Also did you manage to look into my later code which I described as the “better way”

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil ah thanks will look into it no need to apologise mate.

      Did you have a chance to look into my 2 sets of codes ?

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil
      here is the code for trying out the “better” method:

      MMM-MP3Player.js:

      var MP3;
      var substr;
      Module.register("MMM-MP3Player", {
        defaults: {
          songs: [],
          musicPath: "modules/MMM-MP3Player/music",
          extensions: ["mp3", "wma", "acc", "ogg"],
          songs: null,
          autoPlay: false,
          random: false,
        },
        audio: null,
        songTitle: null,
        mediaPlayer: null,
        dataAvailable: true,
        curSong :0,
        curLength : 0,
        time: null,
        play: null,
        firstTime: true,
        substr: null,
        
        getStyles: function(){
          return ["MMM-MP3Player.css", "font-awesome.css"];
        },
      
        start: function(){
          MP3 = this;
          console.log("autoPlay configuration:", MP3.config.autoPlay);
          Log.info("Starting module: " + MP3.name);
        },
      
      getDom: function(){
          var wrapper = document.createElement("div");
      
        if(MP3.config.folders) {
          var folderList = document.createElement("ul");
          folderList.className = "folderList";
      
          MP3.config.folders.forEach((folder, index) => {
            var folderItem = document.createElement("li");
            folderItem.className = "folderItem";
            folderItem.textContent = folder.name;
            folderItem.onclick = function() {
              this.classList.toggle("active");
              var songList = this.nextElementSibling;
              if (!songList) {
                songList = document.createElement("ul");
                songList.className = "songList";
                folder.songs.forEach(song => {
                  var songItem = document.createElement("li");
                  songItem.className = "songItem";
                  songItem.textContent = song.substr(0, song.length - 4); // removes extension
                  songItem.onclick = function() {
                    // Set the song from the specific folder
                    MP3.setCurrentSong(folder.name, song);
                    MP3.audio.play();
                    MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                    MP3.mediaPlayer.classList.add("play");
                    MP3.updateDurationLabel();
                  };
                  songList.appendChild(songItem);
                });
                this.parentNode.insertBefore(songList, this.nextSibling);
              } else {
                songList.parentNode.removeChild(songList);
              }
            };
            folderList.appendChild(folderItem);
          });
          wrapper.appendChild(folderList);
          
              // Add the rest of the existing code...
              MP3.mediaPlayer = MP3.createElement("div", "mediaPlayer", "mediaPlayer");
              MP3.audio = MP3.createElement("audio", "audioPlayer", "audioPlayer");
              MP3.audio.addEventListener("loadeddata", () => {
                  MP3.dataAvailable = true;
                  MP3.curLength = MP3.audio.duration;
                  MP3.updateDurationLabel(); 
              }),
              MP3.audio.addEventListener("ended", () => {
                  Log.log(" play ended")
                  MP3.audio.currentTime = 0;
                  if(MP3.config.autoPlay)
                  {
                      MP3.loadNext(MP3.config.random)
                  }
                  else
                      MP3.mediaPlayer.classList.toggle("play");
              }),
      
      MP3.audio.addEventListener("timeupdate", () => {
        MP3.updateDurationLabel();
      }),
              MP3.mediaPlayer.appendChild(MP3.audio);
      
              // Add the rest of the controls to MP3.mediaPlayer
              var controls = MP3.createElement("div", "controls", false);
              MP3.songTitle = MP3.createElement("span", "title", "songTitle");
              MP3.setCurrentSong(MP3.curSong);
              controls.appendChild(MP3.songTitle);
      
              var discArea = MP3.createElement("div", "discarea", false);
              discArea.appendChild(MP3.createElement("div", "disc", false));
              var stylus = MP3.createElement("div", "stylus", false);
              stylus.appendChild(MP3.createElement("div", "pivot", false));
              stylus.appendChild(MP3.createElement("div", "arm", false));
              stylus.appendChild(MP3.createElement("div", "head", false));
              discArea.appendChild(stylus);
              MP3.mediaPlayer.appendChild(discArea);
      
            var buttons = MP3.createElement("div", "buttons", false);
      
            //  Previous Button
            var prev = MP3.createButton("back", "prevButton", "fa fa-backward");
            prev.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.audio.play();
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
            }, false),
            buttons.appendChild(prev);
      
            //  Play Button
            MP3.play = MP3.createButton("play", "playButton", "fa fa-play");
            MP3.play.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              if (MP3.audio.paused) {
                setTimeout(() => {
                  MP3.audio.play();
                }, 300);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                MP3.timer = setInterval(MP3.updateDurationLabel, 100);
              } else {
                //MP3.loadNext(MP3.config.random);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
                clearInterval(MP3.timer);
                MP3.audio.pause();
              }
            }, false);
            buttons.appendChild(MP3.play);
      
            //  Stop Button
            var stop = MP3.createButton("stop", "stopButton", "fa fa-stop");
            stop.addEventListener("click", () => {
              MP3.mediaPlayer.classList.remove("play");
              MP3.audio.pause();
              MP3.audio.currentTime = 0;
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
              MP3.updateDurationLabel();
            }, false);
            buttons.appendChild(stop);
      
            //  Next Button
            var next = MP3.createButton("next", "nextButton", "fa fa-forward");
            next.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
            }, false);
            buttons.appendChild(next);
      
              controls.appendChild(buttons);
      
              var subControls = MP3.createElement("div", "subControls", false);
              var duration = MP3.createElement("span", "duration", "currentDuration");
              duration.innerHTML = "00:00" + "&nbsp&nbsp&nbsp";
              subControls.appendChild(duration);
      
              var volumeSlider = MP3.createElement("input", "volumeSlider", "volumeSlider");
              volumeSlider.type = "range";
              volumeSlider.min = "0";
              volumeSlider.max = "1";
              volumeSlider.step = "0.01";
              volumeSlider.addEventListener("input", () => {
                  MP3.audio.volume = parseFloat(volumeSlider.value);
              }, false);
      
              subControls.appendChild(volumeSlider);
              controls.appendChild(subControls);
              MP3.mediaPlayer.appendChild(controls);
      
              wrapper.appendChild(MP3.mediaPlayer);
          }
      
          if(MP3.firstTime && MP3.config.autoPlay){
              console.log("First time and autoPlay are true. Setting firstTime to false.");
              MP3.firstTime=false;
          }
          return wrapper;
      },
      
      setCurrentSong: function(folderName, songName){
        if(MP3.audio!= undefined){
          MP3.audio.src = MP3.config.musicPath + '/' + folderName + '/' + songName;
          MP3.songTitle.innerHTML = songName.substr(0, songName.length - 4); // update song title display
          // Update the current song, handling file paths
          MP3.curSong = MP3.config.folders.findIndex(folder => folder.name === folderName);
        }
      },
      
        createElement: function(type, className, id){
          var elem = document.createElement(type);
          if(className) elem.className = className;
          if(id)  elem.id = id;
          return elem;
        },
      
        createButton: function(className, id, icon){
          var button = document.createElement('button');
          button.className = className;
          button.id = id;
          var ico = document.createElement("i");
          ico.className = icon;
          button.appendChild(ico);
          return button;
        },
      
      updateDurationLabel: function() {
        var duration = document.getElementById('currentDuration');
        if (MP3.dataAvailable && MP3.audio.duration > 0) {
          duration.innerText = MP3.parseTime(MP3.audio.currentTime) + " / " + MP3.parseTime(MP3.audio.duration);
        } else {
          duration.innerText = "00:00 / 00:00";
        }
      },
      
        parseTime: function(time){
          const minutes = Math.floor(time / 60)
          const seconds = Math.floor(time - minutes * 60)
          const secondsZero = seconds < 10 ? "0" : ""
          const minutesZero = minutes < 10 ? "0" : ""
          return minutesZero + minutes.toString() + ":" + secondsZero + seconds.toString()
        },
        
        setCurrentSong: function(index){
            if(MP3.audio!= undefined){
              MP3.audio.src = MP3.config.musicPath + '/' + MP3.config.songs[index];
              MP3.songTitle.innerHTML = MP3.config.songs[index].substr(0, MP3.config.songs[index].length - 4);
              MP3.curSong = index;
            }
        },
        loadNext: function(next){
         let index=0;
            console.log("loadNext: Autoplay:", MP3.config.autoPlay); // Add this line for logging
            MP3.audio.pause();
            if(next)  index= (MP3.curSong + 1) % MP3.config.songs.length;
            else      index = (MP3.curSong - 1) < 0 ? MP3.config.songs.length - 1 : MP3.curSong - 1;
            MP3.setCurrentSong(index);
            MP3.audio.play();
        },
      
        notificationReceived: function (notification, payload) {
          if(notification === "ALL_MODULES_STARTED")
      		  MP3.sendSocketNotification('SOURCE_MUSIC', MP3.config);
        },
        
        socketNotificationReceived: function(notification, payload){
          if(notification === "RETURNED_MUSIC")
            MP3.config.songs = payload.songs;
            // set the initial song index 
            MP3.setCurrentSong(0);
            // paint the player
            MP3.updateDom(2);
        },
      });
      

      and the updated node-helper.js:

      var NodeHelper = require('node_helper');
      const Fs = require('fs');
      const Path = require('path');
      
      module.exports = NodeHelper.create({
        start: function() {
          console.log("Loaded MP3Player node_helper");
        },
        socketNotificationReceived: function(notification, payload){
          var self = this;
          if(notification == 'SOURCE_MUSIC'){
            var folders = this.getFoldersWithSongs(payload.musicPath, payload.extensions);
            self.sendSocketNotification("RETURNED_MUSIC", {folders: folders});
          }
        },
        getFoldersWithSongs: function(path, ext){
          var folders = [];
          var contents = Fs.readdirSync(path, { withFileTypes: true });
          contents.forEach(dirent => {
            if (dirent.isDirectory()) {
              let songFiles = Fs.readdirSync(Path.join(path, dirent.name))
                                .filter(file => this.checkExt(file, ext));
              if (songFiles.length > 0) {
                folders.push({name: dirent.name, songs: songFiles});
              }
            }
          });
          console.log("mp3 player returning folder list with songs="+ folders)
          return folders;
        },
        checkExt: function(file, ext){
          return ext.some(extension => file.toLowerCase().endsWith("." + extension));
        }
      });
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil can you please recommend some editor with brace matching?

      also I added close brace but that didnt resolve the issue got another error now right at the bottom.

      error:

      Uncaught SyntaxError: missing ) after argument list :8182/modules/MMM-MP…MM-MP3Player.js:264
      

      here is line 263 and 264:

      }
      }
      

      here is the full code:

      var MP3;
      var substr;
      Module.register("MMM-MP3Player", {
        defaults: {
          songs: [],
          songs2: [],  // Add this line for the second song list
          musicPath: "modules/MMM-MP3Player/music",
          musicPath2: "modules/MMM-MP3Player/music2",
          extensions: ["mp3", "wma", "acc", "ogg"],
      //    songs: null,
          autoPlay: false,
          random: false,
        },
        audio: null,
        songTitle: null,
        mediaPlayer: null,
        dataAvailable: true,
        curSong :0,
        curLength : 0,
        time: null,
        play: null,
        firstTime: true,
        substr: null,
        
        getStyles: function(){
          return ["MMM-MP3Player.css", "font-awesome.css"];
        },
      
      start: function() {
        MP3 = this;
        console.log("Starting module:", MP3.name);
        this.sendSocketNotification('SOURCE_MUSIC', {musicPath: this.config.musicPath, extensions: this.config.extensions});
        this.sendSocketNotification('SOURCE_MUSIC2', {musicPath: this.config.musicPath2, extensions: this.config.extensions}); // Send notification to load songs from the second directory
      },
      
      getDom: function(){
          var wrapper = document.createElement("div");
      
          if(MP3.config.songs != null) {
              // Display the list of MP3 files
              var songList = MP3.createElement("ul", "songList", "songList");
              for(var i = 0; i < MP3.config.songs.length; i++) {
                  var listItem = MP3.createElement("li", "songItem", "songItem" + i);
                  listItem.innerHTML = MP3.config.songs[i].substr(0, MP3.config.songs[i].length - 4);
                  listItem.addEventListener("click", function(index) {
                      return function() {
                          MP3.setCurrentSong(index);
                          MP3.audio.play();
                          MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                          MP3.mediaPlayer.classList.add("play");
                          MP3.updateDurationLabel();
                      };
                  }(i));
                  songList.appendChild(listItem);
              }
              wrapper.appendChild(songList);
      }
        if (MP3.config.songs2 != null) {
          var songList2 = MP3.createElement("ul", "songList2", "songList2");
          for (var i = 0; i < MP3.config.songs2.length; i++) {
            var listItem = MP3.createElement("li", "songItem2", "songItem2-" + i);
            listItem.innerHTML = MP3.config.songs2[i].substr(0, MP3.config.songs2[i].length - 4);
            listItem.addEventListener("click", function(index) {
              return function() {
                MP3.setCurrentSong(index, 'music2');
                MP3.audio.play();
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                MP3.mediaPlayer.classList.add("play");
                MP3.updateDurationLabel();
              };
            }(i));
            songList2.appendChild(listItem);
          }
          wrapper.appendChild(songList2);
      
              // Add the rest of the existing code...
              MP3.mediaPlayer = MP3.createElement("div", "mediaPlayer", "mediaPlayer");
              MP3.audio = MP3.createElement("audio", "audioPlayer", "audioPlayer");
              MP3.audio.addEventListener("loadeddata", () => {
                  MP3.dataAvailable = true;
                  MP3.curLength = MP3.audio.duration;
                  MP3.updateDurationLabel(); 
              }),
              MP3.audio.addEventListener("ended", () => {
                  Log.log(" play ended")
                  MP3.audio.currentTime = 0;
                  if(MP3.config.autoPlay)
                  {
                      MP3.loadNext(MP3.config.random)
                  }
                  else
                      MP3.mediaPlayer.classList.toggle("play");
              }),
      
      MP3.audio.addEventListener("timeupdate", () => {
        MP3.updateDurationLabel();
      }),
              MP3.mediaPlayer.appendChild(MP3.audio);
      
              // Add the rest of the controls to MP3.mediaPlayer
              var controls = MP3.createElement("div", "controls", false);
              MP3.songTitle = MP3.createElement("span", "title", "songTitle");
              MP3.setCurrentSong(MP3.curSong);
              controls.appendChild(MP3.songTitle);
      
              var discArea = MP3.createElement("div", "discarea", false);
              discArea.appendChild(MP3.createElement("div", "disc", false));
              var stylus = MP3.createElement("div", "stylus", false);
              stylus.appendChild(MP3.createElement("div", "pivot", false));
              stylus.appendChild(MP3.createElement("div", "arm", false));
              stylus.appendChild(MP3.createElement("div", "head", false));
              discArea.appendChild(stylus);
              MP3.mediaPlayer.appendChild(discArea);
      
            var buttons = MP3.createElement("div", "buttons", false);
      
            //  Previous Button
            var prev = MP3.createButton("back", "prevButton", "fa fa-backward");
            prev.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.audio.play();
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
            }, false),
            buttons.appendChild(prev);
      
            //  Play Button
            MP3.play = MP3.createButton("play", "playButton", "fa fa-play");
            MP3.play.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              if (MP3.audio.paused) {
                setTimeout(() => {
                  MP3.audio.play();
                }, 300);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                MP3.timer = setInterval(MP3.updateDurationLabel, 100);
              } else {
                //MP3.loadNext(MP3.config.random);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
                clearInterval(MP3.timer);
                MP3.audio.pause();
              }
            }, false);
            buttons.appendChild(MP3.play);
      
            //  Stop Button
            var stop = MP3.createButton("stop", "stopButton", "fa fa-stop");
            stop.addEventListener("click", () => {
              MP3.mediaPlayer.classList.remove("play");
              MP3.audio.pause();
              MP3.audio.currentTime = 0;
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
              MP3.updateDurationLabel();
            }, false);
            buttons.appendChild(stop);
      
            //  Next Button
            var next = MP3.createButton("next", "nextButton", "fa fa-forward");
            next.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
            }, false);
            buttons.appendChild(next);
      
              controls.appendChild(buttons);
      
              var subControls = MP3.createElement("div", "subControls", false);
              var duration = MP3.createElement("span", "duration", "currentDuration");
              duration.innerHTML = "00:00" + "&nbsp&nbsp&nbsp";
              subControls.appendChild(duration);
      
              var volumeSlider = MP3.createElement("input", "volumeSlider", "volumeSlider");
              volumeSlider.type = "range";
              volumeSlider.min = "0";
              volumeSlider.max = "1";
              volumeSlider.step = "0.01";
              volumeSlider.addEventListener("input", () => {
                  MP3.audio.volume = parseFloat(volumeSlider.value);
              }, false);
      
              subControls.appendChild(volumeSlider);
              controls.appendChild(subControls);
              MP3.mediaPlayer.appendChild(controls);
      
              wrapper.appendChild(MP3.mediaPlayer);
          }
      
          if(MP3.firstTime && MP3.config.autoPlay){
              console.log("First time and autoPlay are true. Setting firstTime to false.");
              MP3.firstTime=false;
          }
          return wrapper;
      },
      
        createElement: function(type, className, id){
          var elem = document.createElement(type);
          if(className) elem.className = className;
          if(id)  elem.id = id;
          return elem;
        },
      
        createButton: function(className, id, icon){
          var button = document.createElement('button');
          button.className = className;
          button.id = id;
          var ico = document.createElement("i");
          ico.className = icon;
          button.appendChild(ico);
          return button;
        },
      
      updateDurationLabel: function() {
        var duration = document.getElementById('currentDuration');
        if (MP3.dataAvailable && MP3.audio.duration > 0) {
          duration.innerText = MP3.parseTime(MP3.audio.currentTime) + " / " + MP3.parseTime(MP3.audio.duration);
        } else {
          duration.innerText = "00:00 / 00:00";
        }
      },
      
        parseTime: function(time){
          const minutes = Math.floor(time / 60)
          const seconds = Math.floor(time - minutes * 60)
          const secondsZero = seconds < 10 ? "0" : ""
          const minutesZero = minutes < 10 ? "0" : ""
          return minutesZero + minutes.toString() + ":" + secondsZero + seconds.toString()
        },
        
      setCurrentSong: function(index, type='music1') {
        var path = type === 'music1' ? MP3.config.musicPath : MP3.config.musicPath2;  // Use musicPath2 from config
        MP3.audio.src = path + '/' + MP3.config['songs' + (type === 'music1' ? '' : '2')][index];
        MP3.songTitle.innerHTML = MP3.config['songs' + (type === 'music1' ? '' : '2')][index].substr(0, MP3.config['songs' + (type === 'music1' ? '' : '2')][index].length - 4);
        MP3.curSong = index;
      },
      
        loadNext: function(next){
         let index=0;
            console.log("loadNext: Autoplay:", MP3.config.autoPlay); // Add this line for logging
            MP3.audio.pause();
            if(next)  index= (MP3.curSong + 1) % MP3.config.songs.length;
            else      index = (MP3.curSong - 1) < 0 ? MP3.config.songs.length - 1 : MP3.curSong - 1;
            MP3.setCurrentSong(index);
            MP3.audio.play();
        },
      
        notificationReceived: function (notification, payload) {
          if(notification === "ALL_MODULES_STARTED")
      		  MP3.sendSocketNotification('SOURCE_MUSIC', MP3.config);
        },
        
      socketNotificationReceived: function(notification, payload) {
        if (notification === "RETURNED_MUSIC") 
          if (payload.type === 'music1') {
            MP3.config.songs = payload.songs;
          } else if (payload.type === 'music2') {
            MP3.config.songs2 = payload.songs;
          }
          MP3.setCurrentSong(0); // set initial song for each list
          MP3.updateDom();
        }
      }
      });
      

      you see all I am trying to do is to add like a playlist to the module so basically I have added the songList and it shows all the songs i.e. .mp3 files in the music folder within the module’s folder.

      I am now adding music2 folder to show another set of mp3 files and I thought of grouping each folder by artist name and display it on the front end.

      this method is tedious as I need to repeat this for many artists.

      a better method I think would be of having several artists folders in the module’s “single” music folder and in each artist’s folder there will be various mp3s.

      this way the module should display the available artist i.e. folders in the front end and when I click on the artist’s name on the front end it would collapse down and show the mp3s in that respective artist’s folder.

      I did try to work on this “better method” but didnt get far so I went for the easier option as I already had a single “songList” which was working and showing the mp3s in the “music” folder.

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil

      its this:

      return wrapper;
      

      which is around here :

      ..........
      
              var volumeSlider = MP3.createElement("input", "volumeSlider", "volumeSlider");
              volumeSlider.type = "range";
              volumeSlider.min = "0";
              volumeSlider.max = "1";
              volumeSlider.step = "0.01";
              volumeSlider.addEventListener("input", () => {
                  MP3.audio.volume = parseFloat(volumeSlider.value);
              }, false);
      
              subControls.appendChild(volumeSlider);
              controls.appendChild(subControls);
              MP3.mediaPlayer.appendChild(controls);
      
              wrapper.appendChild(MP3.mediaPlayer);
          }
      
          if(MP3.firstTime && MP3.config.autoPlay){
              console.log("First time and autoPlay are true. Setting firstTime to false.");
              MP3.firstTime=false;
          }
          return wrapper;
      },
      
        createElement: function(type, className, id){
          var elem = document.createElement(type);
          if(className) elem.className = className;
          if(id)  elem.id = id;
          return elem;
        },
      
      .....
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil

      so I removed it to this:

      socketNotificationReceived: function(notification, payload) {
        if (notification === "RETURNED_MUSIC") {
          if (payload.type === 'music1') {
            MP3.config.songs = payload.songs;
          } else if (payload.type === 'music2') {
            MP3.config.songs2 = payload.songs;
          }
          MP3.setCurrentSong(0); // set initial song for each list
          MP3.updateDom();
        }
      }
      });
      
      

      but still doesnt like it gives this error:

      :8182/modules/MMM-MP…MM-MP3Player.js:196 Uncaught SyntaxError: Unexpected token ','
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil

      Hi Sam thanks for that I will try it out soon.

      I am currently working on the existing mp3 player module and have added another songList i.e. songList2 as per my get dom function. Trouble is I get this error when I restart the MagicMirror, the error is from the developer console. I am scratching my head to resolve it but it doesnt work.

      here is the code:

      MMM-MP3Player.js:

      var MP3;
      var substr;
      Module.register("MMM-MP3Player", {
        defaults: {
          songs: [],
          songs2: [],  // Add this line for the second song list
          musicPath: "modules/MMM-MP3Player/music",
          musicPath2: "modules/MMM-MP3Player/music2",
          extensions: ["mp3", "wma", "acc", "ogg"],
      //    songs: null,
          autoPlay: false,
          random: false,
        },
        audio: null,
        songTitle: null,
        mediaPlayer: null,
        dataAvailable: true,
        curSong :0,
        curLength : 0,
        time: null,
        play: null,
        firstTime: true,
        substr: null,
        
        getStyles: function(){
          return ["MMM-MP3Player.css", "font-awesome.css"];
        },
      
      start: function() {
        MP3 = this;
        console.log("Starting module:", MP3.name);
        this.sendSocketNotification('SOURCE_MUSIC', {musicPath: this.config.musicPath, extensions: this.config.extensions});
        this.sendSocketNotification('SOURCE_MUSIC2', {musicPath: this.config.musicPath2, extensions: this.config.extensions}); // Send notification to load songs from the second directory
      },
      
      getDom: function(){
          var wrapper = document.createElement("div");
      
          if(MP3.config.songs != null) {
              // Display the list of MP3 files
              var songList = MP3.createElement("ul", "songList", "songList");
              for(var i = 0; i < MP3.config.songs.length; i++) {
                  var listItem = MP3.createElement("li", "songItem", "songItem" + i);
                  listItem.innerHTML = MP3.config.songs[i].substr(0, MP3.config.songs[i].length - 4);
                  listItem.addEventListener("click", function(index) {
                      return function() {
                          MP3.setCurrentSong(index);
                          MP3.audio.play();
                          MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                          MP3.mediaPlayer.classList.add("play");
                          MP3.updateDurationLabel();
                      };
                  }(i));
                  songList.appendChild(listItem);
              }
              wrapper.appendChild(songList);
      
        if (MP3.config.songs2 != null) {
          var songList2 = MP3.createElement("ul", "songList2", "songList2");
          for (var i = 0; i < MP3.config.songs2.length; i++) {
            var listItem = MP3.createElement("li", "songItem2", "songItem2-" + i);
            listItem.innerHTML = MP3.config.songs2[i].substr(0, MP3.config.songs2[i].length - 4);
            listItem.addEventListener("click", function(index) {
              return function() {
                MP3.setCurrentSong(index, 'music2');
                MP3.audio.play();
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                MP3.mediaPlayer.classList.add("play");
                MP3.updateDurationLabel();
              };
            }(i));
            songList2.appendChild(listItem);
          }
          wrapper.appendChild(songList2);
      
              // Add the rest of the existing code...
              MP3.mediaPlayer = MP3.createElement("div", "mediaPlayer", "mediaPlayer");
              MP3.audio = MP3.createElement("audio", "audioPlayer", "audioPlayer");
              MP3.audio.addEventListener("loadeddata", () => {
                  MP3.dataAvailable = true;
                  MP3.curLength = MP3.audio.duration;
                  MP3.updateDurationLabel(); 
              }),
              MP3.audio.addEventListener("ended", () => {
                  Log.log(" play ended")
                  MP3.audio.currentTime = 0;
                  if(MP3.config.autoPlay)
                  {
                      MP3.loadNext(MP3.config.random)
                  }
                  else
                      MP3.mediaPlayer.classList.toggle("play");
              }),
      
      MP3.audio.addEventListener("timeupdate", () => {
        MP3.updateDurationLabel();
      }),
              MP3.mediaPlayer.appendChild(MP3.audio);
      
              // Add the rest of the controls to MP3.mediaPlayer
              var controls = MP3.createElement("div", "controls", false);
              MP3.songTitle = MP3.createElement("span", "title", "songTitle");
              MP3.setCurrentSong(MP3.curSong);
              controls.appendChild(MP3.songTitle);
      
              var discArea = MP3.createElement("div", "discarea", false);
              discArea.appendChild(MP3.createElement("div", "disc", false));
              var stylus = MP3.createElement("div", "stylus", false);
              stylus.appendChild(MP3.createElement("div", "pivot", false));
              stylus.appendChild(MP3.createElement("div", "arm", false));
              stylus.appendChild(MP3.createElement("div", "head", false));
              discArea.appendChild(stylus);
              MP3.mediaPlayer.appendChild(discArea);
      
            var buttons = MP3.createElement("div", "buttons", false);
      
            //  Previous Button
            var prev = MP3.createButton("back", "prevButton", "fa fa-backward");
            prev.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.audio.play();
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
            }, false),
            buttons.appendChild(prev);
      
            //  Play Button
            MP3.play = MP3.createButton("play", "playButton", "fa fa-play");
            MP3.play.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              if (MP3.audio.paused) {
                setTimeout(() => {
                  MP3.audio.play();
                }, 300);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-pause";
                MP3.timer = setInterval(MP3.updateDurationLabel, 100);
              } else {
                //MP3.loadNext(MP3.config.random);
                MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
                clearInterval(MP3.timer);
                MP3.audio.pause();
              }
            }, false);
            buttons.appendChild(MP3.play);
      
            //  Stop Button
            var stop = MP3.createButton("stop", "stopButton", "fa fa-stop");
            stop.addEventListener("click", () => {
              MP3.mediaPlayer.classList.remove("play");
              MP3.audio.pause();
              MP3.audio.currentTime = 0;
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
              MP3.updateDurationLabel();
            }, false);
            buttons.appendChild(stop);
      
            //  Next Button
            var next = MP3.createButton("next", "nextButton", "fa fa-forward");
            next.addEventListener("click", () => {
              MP3.mediaPlayer.classList.toggle("play");
              MP3.dataAvailable = false;
              MP3.loadNext(MP3.config.random);
              MP3.play.getElementsByTagName('i')[0].className = "fa fa-play";
            }, false);
            buttons.appendChild(next);
      
              controls.appendChild(buttons);
      
              var subControls = MP3.createElement("div", "subControls", false);
              var duration = MP3.createElement("span", "duration", "currentDuration");
              duration.innerHTML = "00:00" + "&nbsp&nbsp&nbsp";
              subControls.appendChild(duration);
      
              var volumeSlider = MP3.createElement("input", "volumeSlider", "volumeSlider");
              volumeSlider.type = "range";
              volumeSlider.min = "0";
              volumeSlider.max = "1";
              volumeSlider.step = "0.01";
              volumeSlider.addEventListener("input", () => {
                  MP3.audio.volume = parseFloat(volumeSlider.value);
              }, false);
      
              subControls.appendChild(volumeSlider);
              controls.appendChild(subControls);
              MP3.mediaPlayer.appendChild(controls);
      
              wrapper.appendChild(MP3.mediaPlayer);
          }
      
          if(MP3.firstTime && MP3.config.autoPlay){
              console.log("First time and autoPlay are true. Setting firstTime to false.");
              MP3.firstTime=false;
          }
          return wrapper;
      },
      
        createElement: function(type, className, id){
          var elem = document.createElement(type);
          if(className) elem.className = className;
          if(id)  elem.id = id;
          return elem;
        },
      
        createButton: function(className, id, icon){
          var button = document.createElement('button');
          button.className = className;
          button.id = id;
          var ico = document.createElement("i");
          ico.className = icon;
          button.appendChild(ico);
          return button;
        },
      
      updateDurationLabel: function() {
        var duration = document.getElementById('currentDuration');
        if (MP3.dataAvailable && MP3.audio.duration > 0) {
          duration.innerText = MP3.parseTime(MP3.audio.currentTime) + " / " + MP3.parseTime(MP3.audio.duration);
        } else {
          duration.innerText = "00:00 / 00:00";
        }
      },
      
        parseTime: function(time){
          const minutes = Math.floor(time / 60)
          const seconds = Math.floor(time - minutes * 60)
          const secondsZero = seconds < 10 ? "0" : ""
          const minutesZero = minutes < 10 ? "0" : ""
          return minutesZero + minutes.toString() + ":" + secondsZero + seconds.toString()
        },
        
      setCurrentSong: function(index, type='music1') {
        var path = type === 'music1' ? MP3.config.musicPath : MP3.config.musicPath2;  // Use musicPath2 from config
        MP3.audio.src = path + '/' + MP3.config['songs' + (type === 'music1' ? '' : '2')][index];
        MP3.songTitle.innerHTML = MP3.config['songs' + (type === 'music1' ? '' : '2')][index].substr(0, MP3.config['songs' + (type === 'music1' ? '' : '2')][index].length - 4);
        MP3.curSong = index;
      },
      
        loadNext: function(next){
         let index=0;
            console.log("loadNext: Autoplay:", MP3.config.autoPlay); // Add this line for logging
            MP3.audio.pause();
            if(next)  index= (MP3.curSong + 1) % MP3.config.songs.length;
            else      index = (MP3.curSong - 1) < 0 ? MP3.config.songs.length - 1 : MP3.curSong - 1;
            MP3.setCurrentSong(index);
            MP3.audio.play();
        },
      
        notificationReceived: function (notification, payload) {
          if(notification === "ALL_MODULES_STARTED")
      		  MP3.sendSocketNotification('SOURCE_MUSIC', MP3.config);
        },
        
      socketNotificationReceived: function(notification, payload) {
        if (notification === "RETURNED_MUSIC") {
          if (payload.type === 'music1') {
            MP3.config.songs = payload.songs;
          } else if (payload.type === 'music2') {
            MP3.config.songs2 = payload.songs;
          }
          MP3.setCurrentSong(0); // set initial song for each list
          MP3.updateDom();
        }
      },
      });
      

      node-helper.js:

      var NodeHelper = require('node_helper');
      const Fs = require('fs');
      
      module.exports = NodeHelper.create({
        start: function() {
          console.log("Loaded MP3Player node_helper");
        },
      socketNotificationReceived: function(notification, payload){
        var self = this;
        if (notification === 'SOURCE_MUSIC') {
          var songs = this.getSongs(payload.musicPath, payload.extensions);
          self.sendSocketNotification("RETURNED_MUSIC", {songs: songs, type: 'music1'});
        } else if (notification === 'SOURCE_MUSIC2') {
          var songs = this.getSongs(payload.musicPath, payload.extensions);
          self.sendSocketNotification("RETURNED_MUSIC", {songs: songs, type: 'music2'});
        }
      },
      getSongs: function(path, ext){
        var songs = [];
        var contents = Fs.readdirSync(path);
        contents.forEach(file => {
          if (this.checkExt(file, ext)) {  // Use the checkExt function to filter files
            songs.push(file);
          }
        });
        console.log("mp3 player returning song list="+ songs);
        return songs;
      },
      });
      

      the error I get is:

      Uncaught SyntaxError: Unexpected token ',' (at MMM-MP3Player.js:196:2)
      

      which is this

      },
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil what do I do then ?

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil I dont I am afraid.

      Do you think posting the codes on here would be suffice? the node-helper, js and the css files?

      MMM-MP3Player.js:

      var arrPlayed = [];
      var audioElement = null; // Define it here globally
      Module.register("MMM-MP3Player",{
      	defaults: {
      		musicPath: "modules/MMM-MP3Player/music/", 
      		autoPlay: true,
      		random: false,
      		loopList: true,
      	},
      	getStyles: function() {
      		return ["style.css"];
      	},
      
      getDom: function() {
          var self = this;
          var wrapper = document.createElement("div");
          wrapper.id = self.identifier + "_wrapper";
      
      
      
          var player = document.createElement("div");
          player.className = "player";
      
          self.info = document.createElement("div");
          self.info.className = "info";
      
          self.artist = document.createElement("span");
          self.artist.className = "artist";
          self.artist.innerHTML = "MMM-MP3Player";
      
          self.song = document.createElement("span");
          self.song.className = "name";
          self.song.innerHTML = self.config.autoPlay ? "AutoPlay Enabled" : "AutoPlay Disabled";
          self.song.innerHTML += self.config.random ? "<br />Random Enabled" : "<br />Random Disabled";
      
          var progress = document.createElement("div");
          progress.className = "progress-bar";
      
          self.bar = document.createElement("div");
          self.bar.className = "bar";
          progress.appendChild(self.bar);
      
          self.info.appendChild(self.artist);
          self.info.appendChild(self.song);
          self.info.appendChild(progress);
      
          self.album_art = document.createElement("div");
          self.album_art.className = "album-art";
          player.appendChild(self.album_art);
          player.appendChild(self.info);
      
          // Controls container
          var controls = document.createElement("div");
          controls.className = "controls";
      
          // Define buttons and associated notifications
          var buttons = {
              "Play": 'PLAY_MUSIC',
              "Stop": 'STOP_MUSIC',
              "Next": 'NEXT_TRACK',
              "Previous": 'PREVIOUS_TRACK',
              "Random On": 'RANDOM_ON',
              "Random Off": 'RANDOM_OFF'
          };
      
          Object.keys(buttons).forEach(function(key) {
              var button = document.createElement("button");
              button.innerHTML = key;
      button.addEventListener("click",()=>{
          console.log("Button clicked: " + key);
          console.log("Sending notification:", buttons[key], 'some_info');
          self.sendNotification('buttons[key]', 'some_info');
              });
              controls.appendChild(button);
          });
      
          player.appendChild(controls);
      
      
          // Initialize the audio element
          audioElement = document.createElement("audio");
          audioElement.id = self.identifier+"_player";
          wrapper.appendChild(audioElement);
          wrapper.appendChild(player);
      
          setTimeout(function() {
              self.sendSocketNotification("INITIATEDEVICES", self.config);
          }, 3000);
      
          return wrapper;
      },
      	socketNotificationReceived: function(notification, payload){
      		var self = this;
      		switch(notification){
      			case "Error": // Universal error handler
      				self.musicFound = false;
      				console.log("[MMM-MP3Player] Error! ", payload);
      				break;
      			case "Music_Files": // this populates the songs list (array)
      				self.songs = payload;
      				self.current = 0;
      				self.musicFound = true;
      				console.log("[MMM-MP3Player] Music Found");
      				arrPlayed = Array(self.songs.length).fill(false);
      				if (self.config.autoPlay){
      					if (self.config.random){
      						ind = Math.floor(Math.random() * self.songs.length); //(self.current + 1) % self.songs.length;
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      				}
      				break;
      			case "Music_File": // this is called everytime a song is sent from the server
      				//console.log(payload[3]);
      				if (payload[3] == 'music.png') {
      					self.album_art.className = "album-art";
      					self.album_art.classList.add('active');
      				}
      				else {
      					self.album_art.classList.toggle('active');
      					self.album_art.className = "album-art-found";
      					var chngstyle = document.querySelector('.album-art-found').style;
      					chngstyle.setProperty("--backgroundImage", "url('" + payload[3] + "')");
      					//var mystr = window.getComputedStyle(document.querySelector('.album-art-found'), '::before').getPropertyValue('background-image');
      					//console.log(mystr);
      				}
      				
      				// create url of the raw data received and play it
      				audioElement=document.getElementById(self.identifier+"_player");
      				var binaryData = [];
      				binaryData.push(payload[0]);
      				if ((payload[2] = 'mp3') || (payload[2] = 'flac')){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/mpeg"}));
      				}
      				/*else if (payload[2] = 'ogg'){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/ogg"}));
      				}*/
      				else if (payload[2] = 'wav'){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/wav"}));
      				}
      				audioElement.load();
      				audioElement.setAttribute('src', url);
      				audioElement.volume = 1;
      				audioElement.play();
      				self.artist.innerHTML = payload[1][0];
      				self.song.innerHTML = payload[1][1];
      				//self.album_art.classList.add('active');
      				// progress bar (thanks to Michael Foley @ https://codepen.io/mdf/pen/ZWbvBv)
      				var timer;
      				var percent = 0;
      				audioElement.addEventListener("playing", function(_event) {
      					advance(_event.target.duration, audioElement);
      				});
      				audioElement.addEventListener("pause", function(_event) {
      					clearTimeout(timer);
      				});
      				var advance = function(duration, element) {
      					increment = 10/duration
      					percent = Math.min(increment * element.currentTime * 10, 100);
      					self.bar.style.width = percent+'%'
      					startTimer(duration, element);
      				}
      				var startTimer = function(duration, element){ 
      					if(percent < 100) {
      						timer = setTimeout(function (){advance(duration, element)}, 100);
      					}
      				}
      				// next track & loop
      				audioElement.onended = function() {
      					if(!self.musicFound){
      						self.album_art.classList.toggle('active');
      						return;
      					}
      					if (self.config.random){
      						if (!arrPlayed.includes(false)){ // if all files are played
      							if (!self.config.loopList) {
      								self.artist.innerHTML = "Playlist ended";
      								self.song.innerHTML = "";
      								console.log("[MMM-MP3Player] Playlist ended");
      								return;
      							}
      							arrPlayed.fill(false);
      						}
      						do {
      							ind = Math.floor(Math.random() * self.songs.length); //(self.current + 1) % self.songs.length;
      						} while ( (arrPlayed[ind]) || ((ind == self.current) && (self.songs.length>1)) ); //ind == self.current: not to play one song twice - in the end of list and in the beginning of newly created list)
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					else {
      						if(self.current==(self.songs.length-1)){ // if all files are played
      							if (!self.config.loopList){
      								self.artist.innerHTML = "Playlist ended";
      								self.song.innerHTML = "";
      								console.log("[MMM-MP3Player] Playlist ended");
      								return;
      							}
      							self.current = -1;
      						}
      						self.current++;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      				};
      				console.log("[MMM-MP3Player] Music Played");
      				break;
      		}
      	},
      
      notificationReceived: function(notification, payload, sender) {
          console.log("Notification received:", notification);
      		var self = this;
      		if (self.musicFound){
      			switch(notification){
      				case "PLAY_MUSIC":
      					if (audioElement.paused){
      						audioElement.play();
      					}
      					else {
      						self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					}
      					break;
      				case "STOP_MUSIC":
      					audioElement.pause();
      					break;
      				case "NEXT_TRACK":
      					if(!self.musicFound){
      						self.album_art.classList.toggle('active');
      						return;
      					}
      					if (self.config.random){
      						if (!arrPlayed.includes(false)){
      							arrPlayed.fill(false);
      						}
      						do {
      							ind = Math.floor(Math.random() * self.songs.length); // (self.current + 1) % self.songs.length;
      						} while (arrPlayed[ind] || ind == self.current); // ind == self.current: not to play one song twice - in the end of list and in the beginning of newly created list)
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					else {
      						if(self.current==(self.songs.length-1)){ // this assures the loop
      							self.current = -1;
      						}
      						self.current++;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					break;
      				case "PREVIOUS_TRACK":
      					if(self.current==0){ // this assures the loop
      							self.current = (self.songs.length);
      						}
      					self.current--;
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					break;
      				case "RANDOM_ON":
      					self.config.random = true;
      					break;
      				case "RANDOM_OFF":
      					self.config.random = false;
      					break;
      			}
      		}
      	}
      });
      

      node_helper.js:

      /* Magic Mirror Node Helper: MMM-MP3Player
       * By asimhsidd
       *
       * Remade by Pavel Smelov.
       * Version 1.2.0 - 2020.09.14
       * GPLv3 License
       */
      
      const NodeHelper = require("node_helper");
      const ID3 = require('node-id3');
      const path = require('path')
      const fs = require('fs');
      
      var music_files_list = [];
      
      module.exports = NodeHelper.create({
      	socketNotificationReceived: function(notification, payload) {
      		var self = this;
      		switch(notification) {
      			case "INITIATEDEVICES":
      				music_files_list = [];
      				var self = this;
      				self.searchMP3(payload.musicPath);
      				if(music_files_list.length){
      					console.log("[MMM-MP3Player] Found ", music_files_list.length, "track(s)");
      					self.sendSocketNotification("Music_Files",music_files_list);
      				}
      				else {
      					console.log("[MMM-MP3Player] Music may not be found");
      				}
      				break;
      			case "LOADFILE":
      				//console.log('[MMM-MP3Player] trying to play next track');
      				if (fs.existsSync(payload)){
      					fs.readFile(payload, function(err, data) {
      						extension = path.basename(payload).split('.').pop(); //extension = path.extname(payload); //returns ext with dot
      						var cover = '';
      						if (extension == "mp3") {
      							tags = ID3.read(data);
      							if (typeof tags.image != "undefined") {
      								/*var base64String = "";
      								for (var i = 0; i < tags.image.imageBuffer.length; i++) {
      									base64String += String.fromCharCode(tags.image.imageBuffer[i]);
      								}
      								cover = "data:image/" + tags.image.mime + ";base64," + Buffer.from(base64String).toString('base64'); */
      								cover = "data:image/" + tags.image.mime + ";base64," + tags.image.imageBuffer.toString('base64');
      							}
      							if (typeof tags.artist == "undefined" && typeof tags.title == "undefined"){ tags.title = path.basename(payload); }
      						}
      						else {
      							tags = {artist:'', title:path.basename(payload)};
      						}
      						if (cover == '') {
      							if (fs.existsSync(path.join(path.dirname(payload),'cover.jpg'))){
      								cover = path.join('/', path.dirname(payload), 'cover.jpg');
      							}
      							else {
      								cover = "music.png";
      							}
      						}
      						self.sendSocketNotification("Music_File",[data,[tags.artist,tags.title], extension, cover]);
      					});
      				}
      				else {
      					self.sendSocketNotification("Error","File can not be opened");
      				}
      				break;
      		}
      	},
      	searchMP3(startPath){ // thanks to Lucio M. Tato at https://stackoverflow.com/questions/25460574/find-files-by-extension-html-under-a-folder-in-nodejs
      		var self = this;
      		var filter_mp3 = RegExp('.mp3'); // var filter = /.mp3/;
      		var filter_flac = RegExp('.flac');
      		//var filter_ogg = RegExp('.ogg');
      		var filter_wav = RegExp('.wav');
      		if (!fs.existsSync(startPath)){
      			console.log("[MMM-MP3Player] no dir ",startPath);
      			return;
      		}
      		var files=fs.readdirSync(startPath);
      		for(var i=0;i<files.length;i++){
      			var filename=path.join(startPath,files[i]);
      			var stat = fs.lstatSync(filename);
      			if (stat.isDirectory()){
      				self.searchMP3(filename); //recurse
      			}else if ( (filter_mp3.test(filename)) || (filter_flac.test(filename)) /*|| (filter_ogg.test(filename))*/ || (filter_wav.test(filename)) ){
      				music_files_list.push(filename.replace(/\/\/+/g, '/')); // to avoid double slashes (https://stackoverflow.com/questions/23584117/replace-multiple-slashes-in-text-with-single-slash-with-javascript/23584219)
      			}
      		}
      	}
      });
      

      style.css:

      /*
       * player css is amdended version of Shayan's player @ https://codepen.io/shayanea/pen/yvvjya
       * Version 1.2.0 - 2020.09.14
       */
      @import url("https://fonts.googleapis.com/css?family=Fira+Sans");
      
      
      .player {
        font-family: "Fira Sans", Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        position: relative;
        background-color: #fff;
        border-radius: 15px;
        width: 300px;
        height: 80px;
        z-index: 5;
        -webkit-box-shadow: 0px 0px 117px -6px rgba(255,255,255,1);
        -moz-box-shadow: 0px 0px 117px -6px rgba(255,255,255,1);
        box-shadow: 0px 0px 117px -6px rgba(255,255,255,1);
        display: flex;
        /*justify-content: flex-end;  */
      }
      .player .info {
        padding: 15px 0px 0px 90px;
        width:65%;
      }
      .player .info .artist,
      .player .info .name {
      	display: block;
      	line-height: 1.0em;
      }
      .player .info .artist {
        color: #222;
        font-size: 16px;
        margin-bottom: 4px;
      }
      .player .info .name {
        color: #808080; /*#999*/
        font-size: 16px; /*13px*/
        margin-bottom: 8px;
      }
      .player .info .progress-bar {
        background-color: #ddd;
        height: 3px;
        width: 100%;
        position: relative;
      }
      
      .controls {
        display: flex;
        justify-content: space-around; /* Distributes space between buttons */
        padding: 10px;
      }
      
      .controls button {
        padding: 5px 10px;
        font-size: 14px;
        color: white;
        background-color: #666; /* Dark grey button background */
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
      }
      
      .controls button:hover {
        background-color: #777; /* Lighten button on hover */
      }
      
      .controls button:active {
        background-color: #555; /* Darken button on active/click */
      }
      
      
      .player .info .progress-bar .bar {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        background-color: #666;
        transition: all 0.2s ease;
      }
      .player .album-art-found {
        position: absolute;
        left: -10px;
        height: 80px;
        width: 80px;
        /* background-color:white; */
        box-shadow: 0px 0px 20px 5px rgba(0, 0, 0, 0.2);
        transform: scale(1.2);
        transition: all 0.5s ease;
      }
      .player .album-art-found::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-position: center;
        background-repeat: no-repeat;
        background-size: 80px;
        background-image: var(--backgroundImage);
      }
      .player .album-art {
        position: absolute;
        left: -10px;
        height: 80px;
        width: 80px;
        border-radius: 50%;
        background-color:white;
        box-shadow: 0px 0px 20px 5px rgba(0, 0, 0, 0.2);
        transform: scale(1.2);
        transition: all 0.5s ease;
      }
      .player .album-art::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border-radius: 50%;
        background-position: center;
        background-repeat: no-repeat;
        background-size: 50px;
        background-image: url("music.png");
      }
      .player .album-art.active {
        box-shadow: 0px 0px 20px 5px rgba(0, 0, 0, 0.4);
        transform: scale(1.2);
        transition: all 1s ease;
        background: linear-gradient(270deg, #2f987d, #4190bd, #d29b2d, #4bd22d, #d2692d, #9e2dd2, #d22daf, #3f2dd2);
        background-size: 1600% 1600%;
        -webkit-animation: ColorChanger 20s ease infinite;
        -moz-animation: ColorChanger 20s ease infinite;
        animation: ColorChanger 20s ease infinite; 
      }
      .player .album-art.active::before {
        animation: rotation 3s infinite linear;
        -webkit-animation: rotation 3s infinite linear;
        animation-fill-mode: forwards;
      }
      
      @-webkit-keyframes ColorChanger {
          0%{background-position:0% 50%}
          50%{background-position:100% 50%}
          100%{background-position:0% 50%}
      }
      @-moz-keyframes ColorChanger {
          0%{background-position:0% 50%}
          50%{background-position:100% 50%}
          100%{background-position:0% 50%}
      }
      @keyframes ColorChanger { 
          0%{background-position:0% 50%}
          50%{background-position:100% 50%}
          100%{background-position:0% 50%}
      }
      @keyframes rotation {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil

      Nope doesn’t work.

      I feel like going back to the old MP3 Player module that you helped.set up and just changing the css from the disc to something more modern and futuristic with better buttons etc.

      Oh and also adding a playlist of mp3s which should be read from the mp3 folder. Display the module in half where the half on the left displays the playlist and the one on the right displays the player buttons etc.

      Is that possible you think?

      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil Hey Sam

      I did the changes but when i click on the “Play” or any button the mp3 file isnt played and I get this error on the developer console:

      Button clicked: Play
      MMM-MP3Player.js:71 Sending notification: PLAY_MUSIC some_info
      MMM-MP3Player.js:72 Uncaught TypeError: this.sendNotification is not a function
      at HTMLButtonElement. (MMM-MP3Player.js:72:10)

      cdc52353-9e36-4b3b-bf23-39d27cca6cb2-image.png

      here is the updated code:

      var arrPlayed = [];
      var audioElement = null; // Define it here globally
      Module.register("MMM-MP3Player",{
      	defaults: {
      		musicPath: "modules/MMM-MP3Player/music/", 
      		autoPlay: true,
      		random: false,
      		loopList: true,
      	},
      	getStyles: function() {
      		return ["style.css"];
      	},
      
      getDom: function() {
          var self = this;
          var wrapper = document.createElement("div");
          wrapper.id = self.identifier + "_wrapper";
      
      
      
          var player = document.createElement("div");
          player.className = "player";
      
          self.info = document.createElement("div");
          self.info.className = "info";
      
          self.artist = document.createElement("span");
          self.artist.className = "artist";
          self.artist.innerHTML = "MMM-MP3Player";
      
          self.song = document.createElement("span");
          self.song.className = "name";
          self.song.innerHTML = self.config.autoPlay ? "AutoPlay Enabled" : "AutoPlay Disabled";
          self.song.innerHTML += self.config.random ? "<br />Random Enabled" : "<br />Random Disabled";
      
          var progress = document.createElement("div");
          progress.className = "progress-bar";
      
          self.bar = document.createElement("div");
          self.bar.className = "bar";
          progress.appendChild(self.bar);
      
          self.info.appendChild(self.artist);
          self.info.appendChild(self.song);
          self.info.appendChild(progress);
      
          self.album_art = document.createElement("div");
          self.album_art.className = "album-art";
          player.appendChild(self.album_art);
          player.appendChild(self.info);
      
          // Controls container
          var controls = document.createElement("div");
          controls.className = "controls";
      
          // Define buttons and associated notifications
          var buttons = {
              "Play": 'PLAY_MUSIC',
              "Stop": 'STOP_MUSIC',
              "Next": 'NEXT_TRACK',
              "Previous": 'PREVIOUS_TRACK',
              "Random On": 'RANDOM_ON',
              "Random Off": 'RANDOM_OFF'
          };
      
          Object.keys(buttons).forEach(function(key) {
              var button = document.createElement("button");
              button.innerHTML = key;
      button.addEventListener("click",()=>{
          console.log("Button clicked: " + key);
          console.log("Sending notification:", buttons[key], 'some_info');
          this.sendNotification('buttons[key]', 'some_info');
              });
              controls.appendChild(button);
          });
      
          player.appendChild(controls);
      
      
          // Initialize the audio element
          audioElement = document.createElement("audio");
          audioElement.id = self.identifier+"_player";
          wrapper.appendChild(audioElement);
          wrapper.appendChild(player);
      
          setTimeout(function() {
              self.sendSocketNotification("INITIATEDEVICES", self.config);
          }, 3000);
      
          return wrapper;
      },
      	socketNotificationReceived: function(notification, payload){
      		var self = this;
      		switch(notification){
      			case "Error": // Universal error handler
      				self.musicFound = false;
      				console.log("[MMM-MP3Player] Error! ", payload);
      				break;
      			case "Music_Files": // this populates the songs list (array)
      				self.songs = payload;
      				self.current = 0;
      				self.musicFound = true;
      				console.log("[MMM-MP3Player] Music Found");
      				arrPlayed = Array(self.songs.length).fill(false);
      				if (self.config.autoPlay){
      					if (self.config.random){
      						ind = Math.floor(Math.random() * self.songs.length); //(self.current + 1) % self.songs.length;
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      				}
      				break;
      			case "Music_File": // this is called everytime a song is sent from the server
      				//console.log(payload[3]);
      				if (payload[3] == 'music.png') {
      					self.album_art.className = "album-art";
      					self.album_art.classList.add('active');
      				}
      				else {
      					self.album_art.classList.toggle('active');
      					self.album_art.className = "album-art-found";
      					var chngstyle = document.querySelector('.album-art-found').style;
      					chngstyle.setProperty("--backgroundImage", "url('" + payload[3] + "')");
      					//var mystr = window.getComputedStyle(document.querySelector('.album-art-found'), '::before').getPropertyValue('background-image');
      					//console.log(mystr);
      				}
      				
      				// create url of the raw data received and play it
      				audioElement=document.getElementById(self.identifier+"_player");
      				var binaryData = [];
      				binaryData.push(payload[0]);
      				if ((payload[2] = 'mp3') || (payload[2] = 'flac')){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/mpeg"}));
      				}
      				/*else if (payload[2] = 'ogg'){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/ogg"}));
      				}*/
      				else if (payload[2] = 'wav'){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/wav"}));
      				}
      				audioElement.load();
      				audioElement.setAttribute('src', url);
      				audioElement.volume = 1;
      				audioElement.play();
      				self.artist.innerHTML = payload[1][0];
      				self.song.innerHTML = payload[1][1];
      				//self.album_art.classList.add('active');
      				// progress bar (thanks to Michael Foley @ https://codepen.io/mdf/pen/ZWbvBv)
      				var timer;
      				var percent = 0;
      				audioElement.addEventListener("playing", function(_event) {
      					advance(_event.target.duration, audioElement);
      				});
      				audioElement.addEventListener("pause", function(_event) {
      					clearTimeout(timer);
      				});
      				var advance = function(duration, element) {
      					increment = 10/duration
      					percent = Math.min(increment * element.currentTime * 10, 100);
      					self.bar.style.width = percent+'%'
      					startTimer(duration, element);
      				}
      				var startTimer = function(duration, element){ 
      					if(percent < 100) {
      						timer = setTimeout(function (){advance(duration, element)}, 100);
      					}
      				}
      				// next track & loop
      				audioElement.onended = function() {
      					if(!self.musicFound){
      						self.album_art.classList.toggle('active');
      						return;
      					}
      					if (self.config.random){
      						if (!arrPlayed.includes(false)){ // if all files are played
      							if (!self.config.loopList) {
      								self.artist.innerHTML = "Playlist ended";
      								self.song.innerHTML = "";
      								console.log("[MMM-MP3Player] Playlist ended");
      								return;
      							}
      							arrPlayed.fill(false);
      						}
      						do {
      							ind = Math.floor(Math.random() * self.songs.length); //(self.current + 1) % self.songs.length;
      						} while ( (arrPlayed[ind]) || ((ind == self.current) && (self.songs.length>1)) ); //ind == self.current: not to play one song twice - in the end of list and in the beginning of newly created list)
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					else {
      						if(self.current==(self.songs.length-1)){ // if all files are played
      							if (!self.config.loopList){
      								self.artist.innerHTML = "Playlist ended";
      								self.song.innerHTML = "";
      								console.log("[MMM-MP3Player] Playlist ended");
      								return;
      							}
      							self.current = -1;
      						}
      						self.current++;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      				};
      				console.log("[MMM-MP3Player] Music Played");
      				break;
      		}
      	},
      
      notificationReceived: function(notification, payload, sender) {
          console.log("Notification received:", notification);
      		var self = this;
      		if (self.musicFound){
      			switch(notification){
      				case "PLAY_MUSIC":
      					if (audioElement.paused){
      						audioElement.play();
      					}
      					else {
      						self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					}
      					break;
      				case "STOP_MUSIC":
      					audioElement.pause();
      					break;
      				case "NEXT_TRACK":
      					if(!self.musicFound){
      						self.album_art.classList.toggle('active');
      						return;
      					}
      					if (self.config.random){
      						if (!arrPlayed.includes(false)){
      							arrPlayed.fill(false);
      						}
      						do {
      							ind = Math.floor(Math.random() * self.songs.length); // (self.current + 1) % self.songs.length;
      						} while (arrPlayed[ind] || ind == self.current); // ind == self.current: not to play one song twice - in the end of list and in the beginning of newly created list)
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					else {
      						if(self.current==(self.songs.length-1)){ // this assures the loop
      							self.current = -1;
      						}
      						self.current++;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					break;
      				case "PREVIOUS_TRACK":
      					if(self.current==0){ // this assures the loop
      							self.current = (self.songs.length);
      						}
      					self.current--;
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					break;
      				case "RANDOM_ON":
      					self.config.random = true;
      					break;
      				case "RANDOM_OFF":
      					self.config.random = false;
      					break;
      			}
      		}
      	}
      });
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @sdetweil I added some logs and I can see that the notification is sent however its not received, see my updated code below with the result from developer console:

      16ba3f04-2eca-40ca-b983-271f17f463b3-image.png

      updated MMM-MP3Player.js:

      var arrPlayed = [];
      var audioElement = null; // Define it here globally
      Module.register("MMM-MP3Player",{
      	defaults: {
      		musicPath: "modules/MMM-MP3Player/music/", 
      		autoPlay: true,
      		random: false,
      		loopList: true,
      	},
      	getStyles: function() {
      		return ["style.css"];
      	},
      
      getDom: function() {
          var self = this;
          var wrapper = document.createElement("div");
          wrapper.id = self.identifier + "_wrapper";
      
      
      
          var player = document.createElement("div");
          player.className = "player";
      
          self.info = document.createElement("div");
          self.info.className = "info";
      
          self.artist = document.createElement("span");
          self.artist.className = "artist";
          self.artist.innerHTML = "MMM-MP3Player";
      
          self.song = document.createElement("span");
          self.song.className = "name";
          self.song.innerHTML = self.config.autoPlay ? "AutoPlay Enabled" : "AutoPlay Disabled";
          self.song.innerHTML += self.config.random ? "<br />Random Enabled" : "<br />Random Disabled";
      
          var progress = document.createElement("div");
          progress.className = "progress-bar";
      
          self.bar = document.createElement("div");
          self.bar.className = "bar";
          progress.appendChild(self.bar);
      
          self.info.appendChild(self.artist);
          self.info.appendChild(self.song);
          self.info.appendChild(progress);
      
          self.album_art = document.createElement("div");
          self.album_art.className = "album-art";
          player.appendChild(self.album_art);
          player.appendChild(self.info);
      
          // Controls container
          var controls = document.createElement("div");
          controls.className = "controls";
      
          // Define buttons and associated notifications
          var buttons = {
              "Play": 'PLAY_MUSIC',
              "Stop": 'STOP_MUSIC',
              "Next": 'NEXT_TRACK',
              "Previous": 'PREVIOUS_TRACK',
              "Random On": 'RANDOM_ON',
              "Random Off": 'RANDOM_OFF'
          };
      
          Object.keys(buttons).forEach(function(key) {
              var button = document.createElement("button");
              button.innerHTML = key;
      button.addEventListener("click", function() {
          console.log("Button clicked: " + key);
          console.log("Sending notification:", buttons[key], 'some_info');
          self.sendNotification('buttons[key]', 'some_info');
              });
              controls.appendChild(button);
          });
      
          player.appendChild(controls);
      
      
          // Initialize the audio element
          audioElement = document.createElement("audio");
          audioElement.id = self.identifier+"_player";
          wrapper.appendChild(audioElement);
          wrapper.appendChild(player);
      
          setTimeout(function() {
              self.sendSocketNotification("INITIATEDEVICES", self.config);
          }, 3000);
      
          return wrapper;
      },
      	socketNotificationReceived: function(notification, payload){
      		var self = this;
      		switch(notification){
      			case "Error": // Universal error handler
      				self.musicFound = false;
      				console.log("[MMM-MP3Player] Error! ", payload);
      				break;
      			case "Music_Files": // this populates the songs list (array)
      				self.songs = payload;
      				self.current = 0;
      				self.musicFound = true;
      				console.log("[MMM-MP3Player] Music Found");
      				arrPlayed = Array(self.songs.length).fill(false);
      				if (self.config.autoPlay){
      					if (self.config.random){
      						ind = Math.floor(Math.random() * self.songs.length); //(self.current + 1) % self.songs.length;
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      				}
      				break;
      			case "Music_File": // this is called everytime a song is sent from the server
      				//console.log(payload[3]);
      				if (payload[3] == 'music.png') {
      					self.album_art.className = "album-art";
      					self.album_art.classList.add('active');
      				}
      				else {
      					self.album_art.classList.toggle('active');
      					self.album_art.className = "album-art-found";
      					var chngstyle = document.querySelector('.album-art-found').style;
      					chngstyle.setProperty("--backgroundImage", "url('" + payload[3] + "')");
      					//var mystr = window.getComputedStyle(document.querySelector('.album-art-found'), '::before').getPropertyValue('background-image');
      					//console.log(mystr);
      				}
      				
      				// create url of the raw data received and play it
      				audioElement=document.getElementById(self.identifier+"_player");
      				var binaryData = [];
      				binaryData.push(payload[0]);
      				if ((payload[2] = 'mp3') || (payload[2] = 'flac')){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/mpeg"}));
      				}
      				/*else if (payload[2] = 'ogg'){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/ogg"}));
      				}*/
      				else if (payload[2] = 'wav'){
      					var url = window.URL.createObjectURL(new Blob(binaryData, {type: "audio/wav"}));
      				}
      				audioElement.load();
      				audioElement.setAttribute('src', url);
      				audioElement.volume = 1;
      				audioElement.play();
      				self.artist.innerHTML = payload[1][0];
      				self.song.innerHTML = payload[1][1];
      				//self.album_art.classList.add('active');
      				// progress bar (thanks to Michael Foley @ https://codepen.io/mdf/pen/ZWbvBv)
      				var timer;
      				var percent = 0;
      				audioElement.addEventListener("playing", function(_event) {
      					advance(_event.target.duration, audioElement);
      				});
      				audioElement.addEventListener("pause", function(_event) {
      					clearTimeout(timer);
      				});
      				var advance = function(duration, element) {
      					increment = 10/duration
      					percent = Math.min(increment * element.currentTime * 10, 100);
      					self.bar.style.width = percent+'%'
      					startTimer(duration, element);
      				}
      				var startTimer = function(duration, element){ 
      					if(percent < 100) {
      						timer = setTimeout(function (){advance(duration, element)}, 100);
      					}
      				}
      				// next track & loop
      				audioElement.onended = function() {
      					if(!self.musicFound){
      						self.album_art.classList.toggle('active');
      						return;
      					}
      					if (self.config.random){
      						if (!arrPlayed.includes(false)){ // if all files are played
      							if (!self.config.loopList) {
      								self.artist.innerHTML = "Playlist ended";
      								self.song.innerHTML = "";
      								console.log("[MMM-MP3Player] Playlist ended");
      								return;
      							}
      							arrPlayed.fill(false);
      						}
      						do {
      							ind = Math.floor(Math.random() * self.songs.length); //(self.current + 1) % self.songs.length;
      						} while ( (arrPlayed[ind]) || ((ind == self.current) && (self.songs.length>1)) ); //ind == self.current: not to play one song twice - in the end of list and in the beginning of newly created list)
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					else {
      						if(self.current==(self.songs.length-1)){ // if all files are played
      							if (!self.config.loopList){
      								self.artist.innerHTML = "Playlist ended";
      								self.song.innerHTML = "";
      								console.log("[MMM-MP3Player] Playlist ended");
      								return;
      							}
      							self.current = -1;
      						}
      						self.current++;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      				};
      				console.log("[MMM-MP3Player] Music Played");
      				break;
      		}
      	},
      
      notificationReceived: function(notification, payload, sender) {
          console.log("Notification received:", notification);
      		var self = this;
      		if (self.musicFound){
      			switch(notification){
      				case "PLAY_MUSIC":
      					if (audioElement.paused){
      						audioElement.play();
      					}
      					else {
      						self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					}
      					break;
      				case "STOP_MUSIC":
      					audioElement.pause();
      					break;
      				case "NEXT_TRACK":
      					if(!self.musicFound){
      						self.album_art.classList.toggle('active');
      						return;
      					}
      					if (self.config.random){
      						if (!arrPlayed.includes(false)){
      							arrPlayed.fill(false);
      						}
      						do {
      							ind = Math.floor(Math.random() * self.songs.length); // (self.current + 1) % self.songs.length;
      						} while (arrPlayed[ind] || ind == self.current); // ind == self.current: not to play one song twice - in the end of list and in the beginning of newly created list)
      						arrPlayed[ind] = true;
      						self.current = ind;
      					}
      					else {
      						if(self.current==(self.songs.length-1)){ // this assures the loop
      							self.current = -1;
      						}
      						self.current++;
      					}
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					break;
      				case "PREVIOUS_TRACK":
      					if(self.current==0){ // this assures the loop
      							self.current = (self.songs.length);
      						}
      					self.current--;
      					self.sendSocketNotification("LOADFILE", self.songs[self.current]);
      					break;
      				case "RANDOM_ON":
      					self.config.random = true;
      					break;
      				case "RANDOM_OFF":
      					self.config.random = false;
      					break;
      			}
      		}
      	}
      });
      
      posted in Development
      B
      bachoo786
    • RE: MP3 Player

      @mumblebaj well I am trying to implement a “module” which satisfies my needs of playing any mp3 file. I do want to play the Quran but like I said initially it could play any mp3 file.

      I do not have a Github link as of now sorry.

      posted in Development
      B
      bachoo786
    • 1 / 1