本文介绍了音频端播放新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个 webapp,当您使用 ajax/jquery 单击链接时,它会加载和播放音轨.一切正常,但是当曲目结束时,曲目将设置为循环播放,这可以永远持续下去.我希望播放器从数据库中自动加载随机曲目,并在曲目结束时播放.音频是这样设置的.

当您单击它时,我正在使用 jquery 将新曲目加载到 #player div 中.例如;

在我的 player.php 文件中;

我从这里和网上尝试了一些建议,比如添加;

还有这个...

还有这个...

但它们都不起作用.我做错了什么?

更新

感谢@Roko C. Buljan 的贡献,我能够使用以下脚本将新曲目加载到 div#player 中.当曲目结束时,使用 ajax 函数 loadurl 模拟点击,并将新曲目加载到#player.这会加载一个新曲目,但是当该曲目结束时,它不会加载另一首曲目.我该如何解决?

 {$(#randomplay").click();});

Tl;Dr: 使用:audio.addEventListener("ended", playNextFn);

有两种可能:

1.如果客户端没有完整的曲目列表:

在您的服务器上创建一条路由,该路由可以使用随机轨道进行响应,并通过 AJAX 将其作为 JSON 格式发送回客户端,如 {src": bazzz.mp3", name": ";", "group": "", "year": "", "cover": ""}.

const audio = new Audio();//或: document.querySelector('#myAudio');const playRandomFile = () =>{fetch("/api/getRandomSong.php").then(res => res.json).then(data => {audio.src = data.src;音频播放();});};audio.addEventListener(结束",playRandomFile);//♫♪♫...♪♫♪♫♪...♫♪!

希望您知道如何编写 PHP 代码,从数据库 songs 表中获取随机条目并将其作为 JSON 返回.

2.如果客户预先知道所有曲目:

结束"事件上使用JS切换到随机轨道.

const 歌曲 = [{src:xyz.mp3",名称:",组:",年份:",封面:"},{src: "foo.mp3", name: "", group: "", year:"", cover: ""},{src: "bar.mp3", name: "", group: "", year:"", cover: ""},];const 音频 = 新音频();//或: document.querySelector('#myAudio');const playRandomFile = () =>{audio.src = Songs[~~(Math.random() * Songs.length)].src;音频播放();};audio.addEventListener(结束",playRandomFile);//♫♪♫...♪♫♪♫♪...♫♪!

每日提示:您可以直接从 songs 数组中使用 JS 生成 HTML.

完整示例

带有维基媒体音频文件和 HTML 元素:

I have a webapp that loads and plays audio tracks when you click on a link using ajax/jquery. Everything works fine, but when the track ends, the track is set to loop and this can go on forever. I would like the player to autoload a random track from the database and play when one track ends. The audio is setup as such.

<div id="player"><audio title="Audio title" controls loop autoplay controlsList="nodownload" preload="auto" id="myAudio" /><source src="audio.mp3" type="audio/mp3" id="audioID"></div>

Am using jquery to load a new track into the #player div when you click on it. eg;

<a href="javascript:;" onClick="loadurl('player.php?play=audioID','player')">Track One</a>

<script type="text/javascript">

<!-- ajaxified -->
function loadurl(dest, targetID) {

var XMLHttpRequestObject = false;
    if (window.XMLHttpRequest) {
            XMLHttpRequestObject = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            XMLHttpRequestObject = new
            ActiveXObject("Microsoft.XMLHttp");
    }

if(XMLHttpRequestObject) {
            XMLHttpRequestObject.open("GET", dest);
            XMLHttpRequestObject.onreadystatechange = function() {

        if (XMLHttpRequestObject.readyState == 4 &&
            XMLHttpRequestObject.status == 200) {
            document.getElementById(targetID).innerHTML =
            XMLHttpRequestObject.responseText;
            delete XMLHttpRequestObject;
            XMLHttpRequestObject = null;
            }
        }
        XMLHttpRequestObject.send(null);
    }
}

</script>

In my player.php file I have;

<?php
.... fetch track from db where id = $_GET['play']; ......
?>

<audio title="Audio Title" controls loop autoplay controlsList="nodownload" preload="auto" id="myAudio" />
<source src="audio2.mp3" type="audio/mp3" id="audioID">

I've tried several suggestions from here and online like adding;

<script type="text/javascript">

const audio = document.querySelector('myAudio');

audio.onended = (event) => {
  console.log('Video stopped either because 1) it was over, ' +
      'or 2) no further data is available.');
};

</script>

and this...

<script type="text/javascript">
const audio = document.querySelector('myAudio');

audio.addEventListener('ended', (event) => {
  console.log('Video stopped either because 1) it was over, ' +
      'or 2) no further data is available.');
});

</script>

and this...

<script type="text/javascript">
myAudio.addEventListener("ended", function(){
     myAudio.currentTime = 0;
     console.log("ended");
     alert("ended");
});

</script>

But none of them work. What am I doing wrong?

UPDATE

Thanks to contributions by @Roko C. Buljan I was able to use the following script to load a new track into the div#player. When track ends, a click is simulated using the ajax function loadurl and a new track is loaded into #player. This loads a new track but when that track ends, it won't load another track. How can I fix that?

<a href="javascript:;" id="randomplay" onClick="loadurl('player.php?random=1','player')"></a>
<script type="text/javascript">

const audio = document.querySelector('#myAudio');

audio.addEventListener("ended", () => {

        $("#randomplay").click();

    });

</script>
解决方案

Tl;Dr: Use: audio.addEventListener("ended", playNextFn);

There's two possibilities:

1. If the client has not a complete list of tracks:

Create a route on your server that can respond with a random track and send it back via AJAX to the client as JSON like {"src": "bazzz.mp3", "name": "", "group": "", "year": "", "cover": ""}.

const audio = new Audio(); // or: document.querySelector('#myAudio');

const playRandomFile = () => {
  fetch("/api/getRandomSong.php").then(res => res.json).then(data => {
    audio.src = data.src;
    audio.play();
  });
};

audio.addEventListener("ended", playRandomFile); // ♫♪♫...♪♫♪♫♪...♫♪!

Hopefully you know how to write a PHP code that gets a random entry from a database songs table and return it as JSON.

2. If the client knows upfront all the tracks:

Use JS to switch to a random track on "ended" Event.

const songs = [
  {src: "xyz.mp3", name: "", group: "", year:"", cover: ""},
  {src: "foo.mp3", name: "", group: "", year:"", cover: ""},
  {src: "bar.mp3", name: "", group: "", year:"", cover: ""},
];

const audio = new Audio(); // or: document.querySelector('#myAudio');

const playRandomFile = () => {
  audio.src = songs[~~(Math.random() * songs.length)].src;
  audio.play();
};

audio.addEventListener("ended", playRandomFile); // ♫♪♫...♪♫♪♫♪...♫♪!

Tip-of-the-day: you can generate your HTML in JS right out of the songs array.

Full Example

with Wikimedia audio files and a HTML <audio> Element:

const songs = [
  {src: "https://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg", name: "", group: "", year:"", cover: ""},
  {src: "https://upload.wikimedia.org/wikipedia/en/3/39/Metallica_-_Enter_Sandman.ogg", name: "", group: "", year:"", cover: ""},
  {src: "https://upload.wikimedia.org/wikipedia/en/5/5e/U2_One.ogg", name: "", group: "", year:"", cover: ""},
];

const audio = document.querySelector('#myAudio');
const getRandomSong = () => songs[~~(Math.random() * songs.length)];

audio.addEventListener("ended", () => {
  audio.src = getRandomSong().src
  audio.play()
});

audio.src = getRandomSong().src // on DOM ready
<audio id="myAudio" controls></audio>

这篇关于音频端播放新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 23:01