added autoplay/shuffle feature

This commit is contained in:
iou1name 2018-09-14 08:02:24 -04:00
parent 5eb70cefd5
commit fbec8d886e
3 changed files with 40 additions and 2 deletions

View File

@ -4,6 +4,7 @@ Music streaming.
"""
import os
import json
import random
import subprocess
from urllib import parse
@ -11,6 +12,7 @@ from flask import Flask, Response, render_template
from werkzeug.utils import secure_filename
MUSIC_DIR = "/mnt/music/Music"
MUSIC_EXT = ['flac', 'mp3', 'wav', 'm4a']
FFMPEG_CMD = [
'ffmpeg', '-y',
'-loglevel', 'panic',
@ -80,5 +82,19 @@ def get_dir(directory):
return json.dumps(nav_items_new)
@app.route('/get_shuffle')
def shuffle():
"""Returns a randomly selected song from the library."""
item = random.choice(os.listdir(MUSIC_DIR))
path = os.path.join(MUSIC_DIR, item)
while not path.rpartition('.')[2] in MUSIC_EXT:
item = random.choice(os.listdir(path))
if os.path.isdir(os.path.join(path, item)):
path = os.path.join(path, item)
if item.rpartition('.')[2] in MUSIC_EXT:
path = os.path.join(path, item)
return path.replace(MUSIC_DIR, '')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5150)

View File

@ -1,16 +1,36 @@
var httpRequest
function load() {
document.getElementById('player').addEventListener('ended', function() {
if (!document.getElementById('shuffle').checked) { return; }
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState !== XMLHttpRequest.DONE) { return; }
if (httpRequest.status !== 200) { return; }
let track = httpRequest.responseText;
change_track(track);
}
httpRequest.open('GET', '/musik/get_shuffle', true);
httpRequest.send();
});
}
function navigate(item) {
if (/\..{3,5}$/.test(item)) {
change_track(item);
select_track(item);
}
else {
get_dir(item);
}
}
function change_track(item) {
function select_track(item) {
let cd = document.getElementById('currentDirectory').innerText;
let track = cd + item;
change_track(track);
}
function change_track(track) {
let source = document.getElementById('stream');
source.src = '/musik/stream' + track;
let player = document.getElementById('player');

View File

@ -4,6 +4,7 @@
<title>Musik</title>
<link rel="stylesheet" type="text/css" href="/static/musik.css">
<script type="text/javascript" src="/static/musik.js"></script>
<script>window.onload = load;</script>
</head>
<body>
<div id="mainContainer">
@ -22,6 +23,7 @@
<audio id="player" controls>
<source id="stream" src="{{ url_for('stream', track=initial_track) }}" type="audio/ogg">
</audio>
<div><input type="checkbox" id="shuffle">Shuffle</input>
</center>
</div>
</div>