【代码】音乐播放器(flask+html5+js)

flask:读取文件流,yield喂给前端;
html5:audio标签,控制和实现的基础;
js:负责事件和动作处理,audio.src="path/xxx.mp3"发起GET请求。





	MusicPlayer
		
	


	
    {% for song in songs %}
  • {{ song }}
  • {% endfor %}
cycle
00:00/00:00
# main.py
import os
from flask import Flask,send_from_directory,request,current_app,render_template,Response
from getList import song_ls

app = Flask(__name__)
root = 'C:\\Users\\XPS-15\\PycharmProjects\\Practice\\前端\\MusicPlayer\\'


# @app.route('/favicon.ico',methods=['GET'])
# def index():
# 	with open(root+'favicon.ico','rb') as fp:
# 		img = fp.read()
# 	return img

@app.route('/',methods=['GET','POST'])
def index():
	# ls = [i for i in os.listdir('C:\\Users\\XPS-15\\PycharmProjects\\Practice\\前端\\MusicPlayer\\temp\\') if i.endswith('mp3')]
    # print(ls)
    
    # if request.method=='GET': 
    # print((request.data,request.get_data()))
	return render_template("player.html",songs=song_ls)



@app.route('/temp/',methods=['GET','POST'])
def getmusic(name):
	if request.method=='GET':
		def gen_audio():
			ratio = None
			if ':' in name:
				file, ratio = name.split(':')
				p = float(ratio)*os.path.getsize(root+'\\temp\\'+file)
				p = int(p);
				print('======ratio:',ratio,p)
			else:
				file = name
			with open(root+'\\temp\\'+file,'rb') as fp:
				if ratio is not None:
					fp.seek(p,0)
				content = fp.read(1024)
				while content:
					yield content  #yield实现播放,暂停和恢复播放
					content = fp.read(1024)
		return Response(gen_audio(),mimetype="audio/mpeg3")
	else:
		return 'hello'


if __name__ == '__main__':
	app.run(debug=True)

浏览器中输入服务器的ip:port,显示页面:
【代码】音乐播放器(flask+html5+js)_第1张图片

你可能感兴趣的:(【代码】音乐播放器(flask+html5+js))