在JavaScript中防止多个音频同时播放

kknvjkwl  于 2023-05-12  发布在  Java
关注(0)|答案(1)|浏览(235)

我正在挑战我的自我,构建这个没有教程的迷你音乐应用程序,但我有很多问题,所以现在我试图通过点击歌曲的名称来播放每首歌曲,我已经构建了这个对象数组和函数,但我不能使用。

const btns = Array.from(document.querySelectorAll('.song-details'));
const music = [
    {
    img: 'img/2.jpg',
    id:1,
    songName: 'Am I Wrong',
    audio : new Audio('audio/Am-I-wrong.mp3'),
    lyrics: 'Am I wrong lyrics',
    btn: btns[1]
    },
    {
    img: 'img/3.jpg',
    id:2,
    songName: 'Sex,Drugs,Etc',
    audio : new Audio('audio/Sex-Drugs-Etc.mp3'),
    lyrics: 'Way Down We Go',
    
    },
    

    {
    img: 'img/7.jpg',
    id:3,
    songName: 'Me Myself & I ',
    audio : new Audio('audio/Me-Myself-I.mp3'),
    lyrics: 'Me Myself & I lyrics',
    },

    {
    img: 'img/4.jpg',
    id:4,
    songName: 'Blood In The Water',
    audio : new Audio('audio/Blood-In-The-Water.mp3'),
    lyrics: 'Blood In The Water lyrics',  
    },

    {
    img: 'img/3.jpg',
    id:5,
    songName: 'Eastside',
    audio : new Audio('audio/Eastside.mp3'),
    lyrics: 'Eastside lyrics',
    },

    {
    img: 'img/6.jpg',
    id:6,
    songName: 'Everything Black ',
    audio : new Audio('audio/Everything-Black.mp3'),
    lyrics: 'Everything Black  lyrics',
    
    },
    
]

const btnsLoop = () => {
    for (j = 0; j < btns.length; j++) {
        const musicObject = music[j];
        const { img, id, songName, audio, lyrics } = musicObject;
        
    
        btns[j].addEventListener('click', () => {
          
`
 if(musicObject.audio.paused && musicObject.audio.currentTime > 0 &&  !musicObject.audio.ended) {
                musicObject.audio.play();
             } else {
                musicObject.audio.pause();
             }
        })
    }
}

btnsLoop();
lskq00tm

lskq00tm1#

对于您的特定用例,一个可能的解决方案是首先暂停所有音频对象,然后开始播放请求的声音。
因此,在click事件侦听器的回调函数中,获取存储在music数组中的所有音频对象,如下所示:

music.forEach(element => {
});

暂停一下

music.forEach(element => {
    element.audio.pause();
});

下面是一个简单的例子:

const btns = Array.from(document.querySelectorAll('.song-details'));
const music = [{
    id: 1,
    songName: 'Am I Wrong',
    audio: new Audio('https://download.samplelib.com/mp3/sample-12s.mp3'),
  },
  {
    id: 2,
    songName: 'Sex,Drugs,Etc',
    audio: new Audio('https://download.samplelib.com/mp3/sample-15s.mp3'),
  }
];

for (j = 0; j < btns.length; j++) {
  const musicObject = music[j];
  const {
    id,
    songName,
    audio
  } = musicObject;
  btns[j].addEventListener('click', () => {
    music.forEach(element => {
      element.audio.pause();
    });
    musicObject.audio.play();
  });
}
<button class="song-details">Song A</button>
<button class="song-details">Song B</button>

相关问题