MagicMirror Forum
    • Recent
    • Tags
    • Unsolved
    • Solved
    • MagicMirror² Repository
    • Documentation
    • 3rd-Party-Modules
    • Donate
    • Discord
    • Register
    • Login
    A New Chapter for MagicMirror: The Community Takes the Lead
    Read the statement by Michael Teeuw here.

    MP3 Player

    Scheduled Pinned Locked Moved Development
    59 Posts 5 Posters 16.6k Views 4 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • B Offline
      bachoo786 @sdetweil
      last edited by

      @sdetweil what do I do then ?

      S 1 Reply Last reply Reply Quote 0
      • S Offline
        sdetweil @bachoo786
        last edited by

        @bachoo786 change the one line of code

        Sam

        How to add modules

        learning how to use browser developers window for css changes

        mumblebajM 1 Reply Last reply Reply Quote 0
        • mumblebajM Offline
          mumblebaj Module Developer @sdetweil
          last edited by

          @sdetweil and @bachoo786 There is a lot wrong with that code snippets. Can’t make it work the way it stands.

          Check out my modules at: https://github.com/mumblebaj?tab=repositories
          Check my blog-post: https://mumblebaj.xyz/
          Check my MM Container: https://hub.docker.com/repository/docker/mumblebaj/magicmirror/general

          S 1 Reply Last reply Reply Quote 0
          • S Offline
            sdetweil @mumblebaj
            last edited by sdetweil

            @mumblebaj @bachoo786 here is a repo for this module

            it is built with name sensitive constructs, so if you rename the files it will adjust automatically… (except for the css file… today it has no module prefix on its selectors)

            https://github.com/sdetweil/new-MP3Player

            (as I already have a module repo with MMM)

            put some music files in the music folder

            install instructions

            cd ~/MagicMirror/modules
            git clone https://github.com/sdetweil/new-MP3Player
            cd new-MP3Player
            npm install 
            

            change the modulename in config.js if u had the prior code

            Sam

            How to add modules

            learning how to use browser developers window for css changes

            S 1 Reply Last reply Reply Quote 0
            • S Offline
              sdetweil @sdetweil
              last edited by

              I updated the player to get rid of as many global variables as possible

              Sam

              How to add modules

              learning how to use browser developers window for css changes

              B 1 Reply Last reply Reply Quote 0
              • B Offline
                bachoo786 @sdetweil
                last edited by bachoo786

                @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

                },
                
                S 1 Reply Last reply Reply Quote 0
                • S Offline
                  sdetweil @bachoo786
                  last edited by

                  @bachoo786 said in MP3 Player:

                  MP3.updateDom();
                  }
                  },
                  });

                  yep, it’s that trailing comma saying another function is coming

                  Sam

                  How to add modules

                  learning how to use browser developers window for css changes

                  B 1 Reply Last reply Reply Quote 0
                  • B Offline
                    bachoo786 @sdetweil
                    last edited by

                    @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 ','
                    
                    S 1 Reply Last reply Reply Quote 0
                    • S Offline
                      sdetweil @bachoo786
                      last edited by

                      @bachoo786 what is on line 195

                      Sam

                      How to add modules

                      learning how to use browser developers window for css changes

                      B 1 Reply Last reply Reply Quote 0
                      • B Offline
                        bachoo786 @sdetweil
                        last edited by

                        @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;
                          },
                        
                        .....
                        
                        S 1 Reply Last reply Reply Quote 0
                        • S Offline
                          sdetweil @bachoo786
                          last edited by sdetweil

                          @bachoo786 you have a missing close brace

                                  wrapper.appendChild(songList);
                               }   // <-----here
                            if (MP3.config.songs2 != null) {
                          

                          you need to use an editor with brace matching

                          Sam

                          How to add modules

                          learning how to use browser developers window for css changes

                          B 1 Reply Last reply Reply Quote 0
                          • B Offline
                            bachoo786 @sdetweil
                            last edited by bachoo786

                            @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.

                            B 1 Reply Last reply Reply Quote 0
                            • B Offline
                              bachoo786 @bachoo786
                              last edited by

                              @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));
                                }
                              });
                              
                              S 1 Reply Last reply Reply Quote 0
                              • S Offline
                                sdetweil @bachoo786
                                last edited by

                                @bachoo786 sorry, been out

                                for editor, install winsvp or bitwise ssh clients. I like bitwise better myself.

                                both will give you ssh window AND a file manager view from windows over the pi (other system) filesystem

                                then you can double click to edit
                                and save back.

                                I use notepad++ or visual studio code as the editor. you a also install visual studio code o the MagicMirror system, UT then u need vnc or keyboard and mouse . I never edit ON the MagicMirror system anymore

                                Sam

                                How to add modules

                                learning how to use browser developers window for css changes

                                B 1 Reply Last reply Reply Quote 0
                                • B Offline
                                  bachoo786 @sdetweil
                                  last edited by

                                  @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 ?

                                  S 1 Reply Last reply Reply Quote 0
                                  • S Offline
                                    sdetweil @bachoo786
                                    last edited by

                                    @bachoo786 yes,

                                    your function

                                    setCurrentSong: function(folderName, songName){
                                    

                                    takes two parms

                                    on line 264 you called it with one

                                          MP3.setCurrentSong(0);
                                    

                                    Sam

                                    How to add modules

                                    learning how to use browser developers window for css changes

                                    B 1 Reply Last reply Reply Quote 0
                                    • B Offline
                                      bachoo786 @sdetweil
                                      last edited by

                                      @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”

                                      S 1 Reply Last reply Reply Quote 0
                                      • S Offline
                                        sdetweil @bachoo786
                                        last edited by

                                        @bachoo786 I did not look at the better method… cause I don’t know what that means.

                                        I wasn’t looking at design, only syntax

                                        Sam

                                        How to add modules

                                        learning how to use browser developers window for css changes

                                        B 1 Reply Last reply Reply Quote 0
                                        • B Offline
                                          bachoo786 @sdetweil
                                          last edited by

                                          @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?

                                          S 1 Reply Last reply Reply Quote 0
                                          • S Offline
                                            sdetweil @bachoo786
                                            last edited by sdetweil

                                            @bachoo786 ok. I saw the song list 2 and 3, and said
                                            these should be arrays of songlist[][]
                                            but now that u add by artist it would be a hash of hashes
                                            songlist{artist{album}{song}}

                                            so you could access it with
                                            songlist[“artistname”][“album1”][song1"]

                                            or
                                            songlist[song_info]
                                            where song_info is a structure
                                            { artist_name:“…”, albums[{name:“…”, songs:[{…}]]}

                                            Sam

                                            How to add modules

                                            learning how to use browser developers window for css changes

                                            B 1 Reply Last reply Reply Quote 0

                                            Hello! It looks like you're interested in this conversation, but you don't have an account yet.

                                            Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

                                            With your input, this post could be even better 💗

                                            Register Login
                                            • 1
                                            • 2
                                            • 3
                                            • 1 / 3
                                            • First post
                                              Last post
                                            Enjoying MagicMirror? Please consider a donation!
                                            MagicMirror created by Michael Teeuw.
                                            Forum managed by Sam, technical setup by Karsten.
                                            This forum is using NodeBB as its core | Contributors
                                            Contact | Privacy Policy