Home  >  Article  >  Web Front-end  >  js implements a music player compatible with IE, FF, Chrome, Opera and Safari_javascript skills

js implements a music player compatible with IE, FF, Chrome, Opera and Safari_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:14:391028browse

The example in this article describes the js implementation of a music player that is compatible with IE, FF, Chrome, Opera and Safari. Share it with everyone for your reference. The specific implementation method is as follows:

/** 音乐播放器 
* @param obj  播放器id 
* @param file  音频文件 mp3: ogg: 
* @param loop  是否循环 
*/ 
function audioplayer(id, file, loop){ 
  var audioplayer = document.getElementById(id); 
  if(audioplayer!=null){ 
    document.body.removeChild(audioplayer); 
  } 
 
  if(typeof(file)!='undefined'){ 
    if(navigator.userAgent.indexOf("MSIE")>0){// IE 
   
    var player = document.createElement('bgsound'); 
    player.id = id; 
    player.src = file['mp3']; 
    player.setAttribute('autostart', 'true'); 
    if(loop){ 
      player.setAttribute('loop', 'infinite'); 
    } 
    document.body.appendChild(player); 
     
    }else{ // Other FF Chome Safari Opera 
   
    var player = document.createElement('audio'); 
    player.id = id; 
    player.setAttribute('autoplay','autoplay'); 
    if(loop){ 
      player.setAttribute('loop','loop'); 
    } 
    document.body.appendChild(player); 
     
    var mp3 = document.createElement('source'); 
    mp3.src = file['mp3']; 
    mp3.type= 'audio/mpeg'; 
    player.appendChild(mp3); 
     
    var ogg = document.createElement('source'); 
    ogg.src = file['ogg']; 
    ogg.type= 'audio/ogg'; 
    player.appendChild(ogg); 
     
    } 
  } 
} 

Usage example:

var file = []; 
file['mp3'] = '1.mp3'; 
file['ogg'] = '1.ogg'; 
audioplayer('audioplane', file, true); // 播放 
audioplayer('audioplane'); // 停止 

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn