保存变量以在 JavaScript 中进行比较

问题描述 投票:0回答:1

我需要修改此代码,以便当同一首歌的名称在我的 html 的 DOM 中显示 +10 分钟时,它会被自定义名称修改。

发生这种情况是因为我用于广播的软件不允许我发送元数据,因此当我开始广播时,会自动显示收音机播放的最后一首歌曲的静态名称。

我已经尝试了一些使用 setIntervalsetTimeout 函数的想法,但我找不到一种方法来将 html 中显示的歌曲名称保存在变量中,以便我可以将其与 ajax 中获得的名称进行比较Nowplaying 功能。

首先我分享代码中需要修改的重要部分,最后分享完整的代码。

window.onload = function() {

  var page = new Page;
  page.changeTitlePage();
  page.setVolume();

  var player = new Player();
  player.play();

  NowPlaying();

  // Interval to get streaming data in miliseconds

  // Update every 5 seconds
  setInterval(function() {
    NowPlaying();
  }, 5000);

  var coverArt = document.getElementsByClassName('cover-album')[0];
  coverArt.style.height = coverArt.offsetWidth + 'px';

}
// Get current song
function NowPlaying() {
  $.ajax({
    url: PROXYURL + URL_STREAMING3,
    type: "GET",
    success: function(result) {
      if (result.trim() !== '') {
        $("#currentSong").html(result);
      } else {
        $("#currentSong").html('DJ OsiriS in Session');
      }
    }
  });
}

正如您在最后一个函数中看到的,如果我使用 GET 获得的结果是空字符串,则短语“DJ OsiriS in Session”将放置在我的 html 的 currentSong ID 中。 如果显示的歌曲名称保持“静态”10 分钟,我想做同样的事情。 您需要的任何其他信息或 HTML 代码请告诉我,我很乐意分享。

完整代码

/*
The MIT License (MIT)

Github: https://github.com/gsavio

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

window.onload = function () {
    
    var page = new Page;
    page.changeTitlePage();
    page.setVolume();

    var player = new Player();
    player.play();
    
    NowPlaying();
    
    // Interval to get streaming data in miliseconds
    
// Update every 5 seconds
setInterval(function(){
    NowPlaying();
}, 5000);

    var coverArt = document.getElementsByClassName('cover-album')[0];
    coverArt.style.height = coverArt.offsetWidth + 'px';
            
}

// DOM control
function Page() {
    this.changeTitlePage = (title = RADIO_NAME) => {
        document.title = title;
    };

        
    
    this.changeVolumeIndicator = (volume) => {
        document.getElementById('volIndicator').innerHTML = volume;

        if (typeof (Storage) !== 'undefined') {
            localStorage.setItem('volume', volume);
        }
    }

    this.setVolume = function () {
        if (typeof (Storage) !== 'undefined') {
            var volumeLocalStorage = (!localStorage.getItem('volume')) ? 80 : localStorage.getItem('volume');
            document.getElementById('volume').value = volumeLocalStorage;
            document.getElementById('volIndicator').innerHTML = volumeLocalStorage;
        }
    }   
        
    
}

var audio = new Audio(URL_STREAMING2);

// Player control
function Player() {
    this.play = function () {
        audio.play();

        var defaultVolume = document.getElementById('volume').value;

        if (typeof (Storage) !== 'undefined') {
            if (localStorage.getItem('volume') !== null) {
                audio.volume = intToDecimal(localStorage.getItem('volume'));
            } else {
                audio.volume = intToDecimal(defaultVolume);
            }
        } else {
            audio.volume = intToDecimal(defaultVolume);
        }
        document.getElementById('volIndicator').innerHTML = defaultVolume;
    };

    this.pause = function () {
        audio.pause();
    };
}

// On play, change the button to pause
audio.onplay = function () {
    var botao = document.getElementById('playerButton');

    if (botao.className === 'fa fa-play') {
        botao.className = 'fa fa-pause';
    }
}

// On pause, change the button to play
audio.onpause = function () {
    var botao = document.getElementById('playerButton');

    if (botao.className === 'fa fa-pause') {
        botao.className = 'fa fa-play';
    }
}

// Unmute when volume changed
audio.onvolumechange = function () {
    if (audio.volume > 0) {
        audio.muted = false;
    }
}

audio.onerror = function () {
    var confirmacao = confirm('Error on communicate to server. \nClick OK to try again.');

    if (confirmacao) {
        window.location.reload();
    }
}

document.getElementById('volume').oninput = function () {
    audio.volume = intToDecimal(this.value);

    var page = new Page();
    page.changeVolumeIndicator(this.value);
}

function togglePlay() {
    if (!audio.paused) {
        audio.pause();
    } else {
        audio.load();
        audio.play();
    }
}

function volumeUp() {
    var vol = audio.volume;
    if(audio) {
        if(audio.volume >= 0 && audio.volume < 1) {
            audio.volume = (vol + .01).toFixed(2);
        }
    }
}

function volumeDown() {
    var vol = audio.volume;
    if(audio) {
        if(audio.volume >= 0.01 && audio.volume <= 1) {
            audio.volume = (vol - .01).toFixed(2);
        }
    }
}

function mute() {
    if (!audio.muted) {
        document.getElementById('volIndicator').innerHTML = 0;
        document.getElementById('volume').value = 0;
        audio.volume = 0;
        audio.muted = true;
    } else {
        var localVolume = localStorage.getItem('volume');
        document.getElementById('volIndicator').innerHTML = localVolume;
        document.getElementById('volume').value = localVolume;
        audio.volume = intToDecimal(localVolume);
        audio.muted = false;
    }
}

// Get current song
function NowPlaying(){
        $.ajax({
        url: PROXYURL + URL_STREAMING3, 
        type: "GET",
        success: function(result) {
            if(result.trim()!==''){
                $("#currentSong").html(result);
                } else {
                $("#currentSong").html('DJ OsiriS in Session'); 
            }
        }
    });
}

    

        
// Player control by keys
document.addEventListener('keydown', function (k) {
    var k = k || window.event;
    var key = k.keyCode || k.which;
    
    var slideVolume = document.getElementById('volume');

    var page = new Page();

    switch (key) {
        // Arrow up
        case 38:
            volumeUp();
            slideVolume.value = decimalToInt(audio.volume);
            page.changeVolumeIndicator(decimalToInt(audio.volume));
            break;
        // Arrow down
        case 40:
            volumeDown();
            slideVolume.value = decimalToInt(audio.volume);
            page.changeVolumeIndicator(decimalToInt(audio.volume));
            break;
        // Spacebar
        case 32:
            togglePlay();
            break;
        // P
        case 80:
            togglePlay();
            break;
        // M
        case 77:
            mute();
            break;
        // 0
        case 48:
            audio.volume = 0;
            slideVolume.value = 0;
            page.changeVolumeIndicator(0);
            break;
        // 0 numeric keyboard
        case 96:
            audio.volume = 0;
            slideVolume.value = 0;
            page.changeVolumeIndicator(0);
            break;
        // 1
        case 49:
            audio.volume = .1;
            slideVolume.value = 10;
            page.changeVolumeIndicator(10);
            break;
        // 1 numeric key
        case 97:
            audio.volume = .1;
            slideVolume.value = 10;
            page.changeVolumeIndicator(10);
            break;
        // 2
        case 50:
            audio.volume = .2;
            slideVolume.value = 20;
            page.changeVolumeIndicator(20);
            break;
        // 2 numeric key
        case 98:
            audio.volume = .2;
            slideVolume.value = 20;
            page.changeVolumeIndicator(20);
            break;
        // 3
        case 51:
            audio.volume = .3;
            slideVolume.value = 30;
            page.changeVolumeIndicator(30);
            break;
        // 3 numeric key
        case 99:
            audio.volume = .3;
            slideVolume.value = 30;
            page.changeVolumeIndicator(30);
            break;
        // 4
        case 52:
            audio.volume = .4;
            slideVolume.value = 40;
            page.changeVolumeIndicator(40);
            break;
        // 4 numeric key
        case 100:
            audio.volume = .4;
            slideVolume.value = 40;
            page.changeVolumeIndicator(40);
            break;
        // 5
        case 53:
            audio.volume = .5;
            slideVolume.value = 50;
            page.changeVolumeIndicator(50);
            break;
        // 5 numeric key
        case 101:
            audio.volume = .5;
            slideVolume.value = 50;
            page.changeVolumeIndicator(50);
            break;
        // 6 
        case 54:
            audio.volume = .6;
            slideVolume.value = 60;
            page.changeVolumeIndicator(60);
            break;
        // 6 numeric key
        case 102:
            audio.volume = .6;
            slideVolume.value = 60;
            page.changeVolumeIndicator(60);
            break;
        // 7
        case 55:
            audio.volume = .7;
            slideVolume.value = 70;
            page.changeVolumeIndicator(70);
            break;
        // 7 numeric key
        case 103:
            audio.volume = .7;
            slideVolume.value = 70;
            page.changeVolumeIndicator(70);
            break;
        // 8
        case 56:
            audio.volume = .8;
            slideVolume.value = 80;
            page.changeVolumeIndicator(80);
            break;
        // 8 numeric key
        case 104:
            audio.volume = .8;
            slideVolume.value = 80;
            page.changeVolumeIndicator(80);
            break;
        // 9
        case 57:
            audio.volume = .9;
            slideVolume.value = 90;
            page.changeVolumeIndicator(90);
            break;
        // 9 numeric key
        case 105:
            audio.volume = .9;
            slideVolume.value = 90;
            page.changeVolumeIndicator(90);
            break;
    }
});

function intToDecimal(vol) {
    return vol / 100;
}

function decimalToInt(vol) {
    return vol * 100;
}

// Encode UTF-8 to URI
function urlencode(str) { 
    str = (str + '') 
    .toString(); 
    
    return encodeURIComponent(str) 
    .replace(/!/g, '%21') 
    .replace(/'/g, '%27') 
    //.replace(/\(/g, '%28') 
    //.replace(/\)/g, '%29') 
    .replace(/\*/g, '%2A') 
    .replace(/%20/g, '+');  
} 

//Capital letter in 1st letter of each word
function ucwords(sentence){
    return sentence.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1){
       return $1.toUpperCase(); 
    });
}

//Capital insensitive comparison
 String.prototype.equalIgnoreCase = function(str)
{
    return (str != null 
            && typeof str === 'string'
            && this.toUpperCase() === str.toUpperCase());
}

//check if a string is empty, null or undefined
 function isEmpty(str) {
    return (!str || 0 === str.length);
}
//check if a string is blank, null or undefined
function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

我等待您的善意评论,以便我可以学习执行这项任务。

javascript dom
1个回答
0
投票

使用全局变量来保存最后一个标题以及首次收到该标题的时间。

var lastTitle, lastTitleTime;

// Get current song
function NowPlaying() {
  $.ajax({
    url: PROXYURL + URL_STREAMING3,
    type: "GET",
    success: function(result) {
      let title = result.trim();
      if (title !== '') {
        if (title !== lastTitle) {
          lastTitle = title;
          lastTitleTime = Date.now();
        } else if (Date.now() > lastTitleTime + 10 * 60 * 1000) {
          title = 'DJ Osiris in Session';
        }
      } else {
        title = 'DJ Osiris in Session';
      }
      $("#currentSong").html(title);
    }
  });
}

© www.soinside.com 2019 - 2024. All rights reserved.