Flask框架中⾳乐播放器的编写(福利篇)1、后端代码
from flask import Flask, render_template
import os
import re
app = Flask(__name__)
@ute('/music')
def music():
path = os.path.dirname(os.path.abspath(__file__))
path = path + '/static/music/'
all_files = os.listdir(path)
music_list = []
for i in all_files:
x = re.findall(r'(.*?).mp3', i)
music_list.append(x[0])
return render_template('other_file_None/music.html', music_list=music_list)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
2、前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>⾳乐</title>
<script src="/static/js/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div  hidden id="value_div">{% for i in music_list %}{{ i +','}}{% endfor %}</div>
html播放音乐代码
<div class="div1" >
<p id = "music_name" >{{ music_list[0] }}</p><br>
<audio id = "audio" src="/static/music/{{ music_list[0] }}.mp3" controls autoplay="true"></audio><br/>
<div >
<button id="btn-play" onclick="play_music()">播放</button>
<button id="btn-stop" onclick="pause_music()">暂停</button>
<button id="btn-pre" onclick="top_music()">上⼀⾸</button>
<button id="btn-next" onclick="next_music()">下⼀⾸</button>
</div>
</div>
<script language="javascript">
var value_music = ElementById("value_div").innerHTML;//获取隐藏div标签中的值
var x = value_music.split(",");//形成js中数组的形式
var audio = ElementById("audio");
var music = new Array(x.length-1);//减1是为了去掉数组中⽂字为空的。
music = x;
var num = 0;
var music_name = ElementById("music_name");
{#播放⾳乐#}
function play_music() {
if(audio.paused){
audio.play();
}
}
{#暂停⾳乐#}
function pause_music() {
function pause_music() {
if(audio.played){
audio.pause();
}
}
{#上⼀⾸⾳乐#}
function top_music() {
num = (num +(x.length-2))% (x.length-1);
if(typeof(music[num])==="undefined" || music[num]===""){            audio.src = "/static/music/" + music[1] + ".mp3";
music_name.innerHTML = music[1];
audio.play();
}else {
audio.src = "/static/music/" + music[num] + ".mp3";
music_name.innerHTML = music[num];
audio.play();
}
}
{#下⼀⾸⾳乐#}
function next_music() {
num = (num +(x.length+2))% (x.length+1);
if(typeof(music[num])==="undefined" || music[num]===""){        audio.src ="/static/music/" + music[2]+".mp3";
music_name.innerHTML = music[2];
audio.play();
}else {
audio.src ="/static/music/" + music[num]+".mp3";
music_name.innerHTML = music[num];
audio.play();
}
}
<!--⾃动播放下⼀⾸-->
audio.addEventListener('ended', function () {
next_music();
}, false);
</script>
</body>
</html>
3、参考⽂档

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。