Optimize the request method and add the function of loading local music on the original music player.
Effect:
Table of contents
The front end is changed to a post request
Add post verification on the view side
Feature List Script Implementation
Playlist Optimization
The original get request is changed to a post request.
set csrf_token
Set the csrf_token tag in the body tag
{% csrf_token %}
The front end is changed to a post request
On the basis of the original player.js song class, change the song list variable to ajax to get it through the back-end interface, and call and set the song information list in the song class constructor.
Note: Because the post request is used, the django csrf token needs to be loaded, otherwise a 403 response will appear.
// 获取歌曲列表
getSongs(){
let mp3list = [];
let csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
type: 'POST',
url: "/media_list",
data: {id: 1, csrfmiddlewaretoken: csrf},
dataType: 'json',
success: function (data) {
mp3list = data.list;
// 将mp3list赋值给this.songs
this.songs = mp3list;
// 调用渲染歌曲列表的方法
this.renderSongList();
}.bind(this),
error: function (e) {
console.log("ERROR : ", e);
}
});
}
Add post verification on the view side
from django.views.decorators.http import require_http_methods
@require_http_methods(['POST'])
def media_list(request):
""" MP3音乐列表 """
mediaList = Single.objects.all()
arr = []
for item in mediaList:
arr.append({
'id': item.id,
'title': item.title,
'singer': item.singer,
'songUrl': item.songUrl,
'imageUrl': item.imageUrl,
})
return JsonResponse({'list': arr})
load song
Added the function of loading songs on the original basis. In the past, it was necessary to manually add the song information to the database. After the modification, you can put the song into the static/media directory, and click the load song function of the player to add the corresponding song to the database.
view
Find all song information in the resource directory, load and import non-duplicate song information.
def load_music(request):
""" 加载本地的歌曲 """
# 项目路径
app_path = os.path.abspath(os.path.dirname(__file__))
# 获取媒体资源目录下所有歌曲文件
path = app_path + '/../static/media/'
files = os.listdir(path)
for file in files:
print(insert_music(file))
return HttpResponse('加载本地音乐成功!')
def insert_music(name):
""" 把歌曲信息插入数据表 """
# 查询歌曲是否存在
info = Single.objects.filter(title=name).first()
if info:
return True
ext = 'mp3'
# 判断文件后缀
fileInfo = name.split('.')
if len(fileInfo) != 2:
return False
if fileInfo[1] != ext:
return False
single = Single()
single.title = name
signers = name.split('-')
single_1 = signers[1].strip('') if len(signers) > 1 else ''
single.singer = single_1.strip('.mp3')
single.songUrl = '/static/media/' + name
# 随机1-10专辑封面图片
sui_num = random.randint(1, 10)
single.imageUrl = '/static/images/' + str(sui_num) + '.png'
return single.save()
set routing
path(r'load_music', views.load_music, name='load_music'),
template
load layui css
<link rel="stylesheet" type="text/css" media="screen"
href="{% static 'css/layui.css' %}">
load layui.js
<script src="{% static 'js/layui.js' %}"></script>
Add function list
Increase function list under blurred background in player body
<!-- 模糊背景 -->
<div class="music-player__blur" style="background-image: url("/static/images/c.jpg");"></div>
<!-- 导入本地歌曲 -->
<div class="music-find_list layui-btn-container">
<span id="btn_list" class="layui-icon layui-icon-app demo1"></span>
</div>
Feature List Script Implementation
<script>
layui.use(['dropdown', 'util', 'layer', 'table'], function(){
var dropdown = layui.dropdown
,util = layui.util
,layer = layui.layer
,$ = layui.jquery;
//初演示
dropdown.render({
elem: '.demo1'
,data: [{
title: '加载歌曲'
,id: 100
}]
,click: function(obj){
loadMusic()
//layer.tips('点击了:'+ obj.title, this.elem, {tips: [1, '#5FB878']})
}
});
// 请求接口 导入歌曲到数据库
function loadMusic() {
$.ajax({
type: 'GET',
url: "/load_music",
data: {id:1},
success: function (data) {
layer.alert(data, {icon: 1})
}.bind(this),
error: function (e) {
console.log("ERROR : ", e);
}
});
}
})
</script>
Effect
final effect
Access through the browser after starting the server, the song can be played and the corresponding song can be switched;
It is also possible to load local songs through the function list.
Project source code:
Link: https://pan.baidu.com/s/1OgqJRMObzZWY4MOwVYdScg
Extraction code: v53n
Summarize
I originally planned to make a more complex web music player website, because I have been busy with work recently, so I first made a simple player to practice. It mainly implements a simple music player function. Because of time constraints, I directly find a ready-made music player template and modify it through django, so the effect is better. The basic functions of the music player have been implemented.