如何在javascript中制作播放页面中所有音频文件样本的按钮?

时间:2017-12-13 21:50:17

标签: javascript html dom audio

我的代码可以动态加载目录中的音频文件。现在他们在点击div时播放/暂停。这是我的javascript:

function get_list_of_files_from_html( html_string ){
       var el = document.createElement( 'html' );
       el.innerHTML = html_string;

       var list_of_files = el.getElementsByTagName( 'a' ); 

     var return_string ='<UL>';

       for(var i=5; i < list_of_files.length ; i++){
           var current_string = list_of_files[i];
           var new_string  = 
 current_string.toString().replace
(/http:\/\/www.website.com\/~user\/programming\//g,'');
           var brand_new = new_string.replace('.mp3','');
            return_string += '<div class="floating"    
onclick="playAudio(\'audio_tag_id'+i+'\')" >'+brand_new+'<audio 
id="audio_tag_id'+i+'"> <source src = "'+current_string+'" 
type="audio/mpeg"></audio>';
             return_string += '</div>';
       }


            return return_string;
        }

function playAudio(tag_id){
  var audio= document.getElementById(tag_id);
return audio.paused ? audio.play() : audio.pause();
}

我想创建一个按钮,每个音频文件只播放五秒钟,然后按顺序运行。有谁知道我会怎么做呢?

1 个答案:

答案 0 :(得分:0)

您需要异步工作,因此它是主代码和回调之间的乒乓。像这样:

// The click event handler 
function onPlayClicked(event){ 
    if (!window.HTMLAudioElement){
        console.write("Error: no audio"); 
        return;
    }

    // toggle the state of the playlist not the actual music player
    isPlaying = !isPlaying; 
    if (isPlaying) startPlaying();
    else resetList();  // if clicked while playing
}

// sets timer and plays current
function startPlaying(){  
    if (isPlaying){ // just checking that no one pressed the STOP in the meantime...
      setTimout(done, 5000); // timer callback and miliseconds
      playAudio(); 
    }
}


// stops this song and starts next. Callback from timer 
function done(){
    if (nowPlaying == lastSongIndex(){
        pauseAudio();
        resetPlaylist();
        return;
    }
    if (isPlaying){
       pauseAudio();
       nowPlaying++;
       startPlaying();
}

// plays current audio
function playAudio(){
    // Friendly advice: don't use getElementByTag. There may be other 'a's. 
    audioList = document.getElementById('audiolist');
    audioURL = audioList[nowPlaying]; // nowPlaying advanced by done()
    urlregex = '/http:\/\/www.website.com\/~user\/programming\//g';
    audioData = audioUrl.remove(urlregex).replace('.mp3','');

    player = document.getElementById('audioplayer');
    player.src = audioData;
    player.play();
}

function pauseAudio(){
    player = document.getElementById('audioplayer');
    player.pause();
}

function reset(){
    pauseAudio();
    nowPlaying = 0;
    isPlaying = false;
    // Unpress the button 
}
// you can easily fill in the rest. 

要了解HTML5中的音频控制,请参阅w3schools上的this for an overview和同一网站上的此as an example

另请注意友好评论:Javascript使用camelCase作为约定,而不是像Python中那样使用snake_case。