From fbec8d886ebfc1abf1859fa65ffe93c3a556af77 Mon Sep 17 00:00:00 2001 From: iou1name Date: Fri, 14 Sep 2018 08:02:24 -0400 Subject: [PATCH] added autoplay/shuffle feature --- musik.py | 16 ++++++++++++++++ static/musik.js | 24 ++++++++++++++++++++++-- templates/index.html | 2 ++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/musik.py b/musik.py index 410bd60..c4de89c 100755 --- a/musik.py +++ b/musik.py @@ -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) diff --git a/static/musik.js b/static/musik.js index 878ddb7..e2f3bfa 100644 --- a/static/musik.js +++ b/static/musik.js @@ -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'); diff --git a/templates/index.html b/templates/index.html index 505f967..4d7200d 100644 --- a/templates/index.html +++ b/templates/index.html @@ -4,6 +4,7 @@ Musik +
@@ -22,6 +23,7 @@ +
Shuffle