Repository navigation
Expand file tree
/
Copy pathmain_v3.py
More file actions
503 lines (396 loc) · 15.6 KB
/
Copy pathmain_v3.py
File metadata and controls
503 lines (396 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import sys
import os
from pathlib import Path
from PySide6.QtCore import Qt, QThread, Signal
from PySide6.QtGui import QKeySequence, QShortcut, QIcon
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QLineEdit, QListWidget, QListWidgetItem,
QFileDialog, QComboBox, QSlider, QMessageBox, QSplitter,
QFrame
)
import pygame
AUDIO_EXTENSIONS = {
".wav", ".mp3", ".ogg", ".flac", ".aac", ".m4a", ".wma"
}
class Scanner(QThread):
found = Signal(str, str, str) # full path, relative path, category
finished = Signal(int)
def __init__(self, root):
super().__init__()
self.root = Path(root)
def run(self):
count = 0
try:
for path in self.root.rglob("*"):
if path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS:
try:
relative = path.relative_to(self.root)
parts = relative.parts
category = parts[0] if len(parts) > 1 else "Root"
self.found.emit(str(path), str(relative), category)
count += 1
except (OSError, ValueError):
pass
finally:
self.finished.emit(count)
class AudioLibrary(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Audio Library Browser")
self.resize(1100, 700)
self.root_folder = None
self.sounds = []
self.current_path = None
self.current_index = -1
self.visible_sounds = []
self.collapsed_folders = set()
pygame.mixer.init()
self.build_ui()
self.setup_shortcuts()
def build_ui(self):
central = QWidget()
self.setCentralWidget(central)
main = QVBoxLayout(central)
main.setContentsMargins(14, 14, 14, 14)
main.setSpacing(10)
# Top bar
top = QHBoxLayout()
title = QLabel("🔊 Audio Library Browser")
title.setStyleSheet("font-size: 20px; font-weight: 700;")
top.addWidget(title)
top.addStretch()
self.folder_label = QLabel("No folder selected")
self.folder_label.setStyleSheet("color: #888;")
top.addWidget(self.folder_label)
choose = QPushButton("Choose Library")
choose.clicked.connect(self.choose_folder)
top.addWidget(choose)
main.addLayout(top)
# Search/filter row
filters = QHBoxLayout()
self.search = QLineEdit()
self.search.setPlaceholderText("Search sounds...")
self.search.textChanged.connect(self.refresh_list)
filters.addWidget(self.search, 2)
self.category = QComboBox()
self.category.addItem("All Categories")
self.category.currentTextChanged.connect(self.refresh_list)
filters.addWidget(self.category, 1)
main.addLayout(filters)
# Main content
splitter = QSplitter(Qt.Horizontal)
left = QFrame()
left_layout = QVBoxLayout(left)
left_layout.setContentsMargins(8, 8, 8, 8)
header_row = QHBoxLayout()
self.count_label = QLabel("0 sounds")
self.count_label.setStyleSheet("font-weight: 600;")
header_row.addWidget(self.count_label)
header_row.addStretch()
self.collapse_btn = QPushButton("Collapse All")
self.collapse_btn.clicked.connect(self.collapse_all)
header_row.addWidget(self.collapse_btn)
self.expand_btn = QPushButton("Expand All")
self.expand_btn.clicked.connect(self.expand_all)
header_row.addWidget(self.expand_btn)
left_layout.addLayout(header_row)
self.list = QListWidget()
self.list.itemClicked.connect(self.list_item_clicked)
self.list.setAlternatingRowColors(True)
self.list.itemDoubleClicked.connect(self.play_selected)
self.list.currentRowChanged.connect(self.selection_changed)
left_layout.addWidget(self.list)
splitter.addWidget(left)
# Right details/player panel
right = QFrame()
right_layout = QVBoxLayout(right)
right_layout.setContentsMargins(20, 20, 20, 20)
self.name_label = QLabel("Select a sound")
self.name_label.setWordWrap(True)
self.name_label.setStyleSheet("font-size: 22px; font-weight: 700;")
right_layout.addWidget(self.name_label)
self.path_label = QLabel("")
self.path_label.setWordWrap(True)
self.path_label.setStyleSheet("color: #888;")
right_layout.addWidget(self.path_label)
# File actions
file_actions = QHBoxLayout()
self.open_location_btn = QPushButton("📂 Open Location")
self.open_location_btn.clicked.connect(self.open_location)
self.open_location_btn.setEnabled(False)
file_actions.addWidget(self.open_location_btn)
self.copy_path_btn = QPushButton("📋 Copy Path")
self.copy_path_btn.clicked.connect(self.copy_path)
self.copy_path_btn.setEnabled(False)
file_actions.addWidget(self.copy_path_btn)
right_layout.addLayout(file_actions)
right_layout.addStretch()
controls = QHBoxLayout()
self.prev_btn = QPushButton("◀ Previous")
self.prev_btn.clicked.connect(self.previous_sound)
controls.addWidget(self.prev_btn)
self.play_btn = QPushButton("▶ Play")
self.play_btn.clicked.connect(self.toggle_play)
self.play_btn.setMinimumHeight(42)
controls.addWidget(self.play_btn)
self.stop_btn = QPushButton("■ Stop")
self.stop_btn.clicked.connect(self.stop)
controls.addWidget(self.stop_btn)
self.next_btn = QPushButton("Next ▶")
self.next_btn.clicked.connect(self.next_sound)
controls.addWidget(self.next_btn)
right_layout.addLayout(controls)
volume_row = QHBoxLayout()
volume_row.addWidget(QLabel("Volume"))
self.volume = QSlider(Qt.Horizontal)
self.volume.setRange(0, 100)
self.volume.setValue(80)
self.volume.valueChanged.connect(self.set_volume)
volume_row.addWidget(self.volume)
right_layout.addLayout(volume_row)
hint = QLabel("Space: play/pause ↑/↓: navigate Enter: play Esc: stop")
hint.setStyleSheet("color: #888;")
right_layout.addWidget(hint)
splitter.addWidget(right)
splitter.setSizes([650, 350])
main.addWidget(splitter, 1)
self.status = QLabel("Choose your audio collection folder to begin.")
self.status.setStyleSheet("color: #888;")
main.addWidget(self.status)
def setup_shortcuts(self):
QShortcut(QKeySequence(Qt.Key_Space), self, activated=self.toggle_play)
QShortcut(QKeySequence(Qt.Key_Return), self, activated=self.play_selected)
QShortcut(QKeySequence(Qt.Key_Enter), self, activated=self.play_selected)
QShortcut(QKeySequence(Qt.Key_Escape), self, activated=self.stop)
QShortcut(QKeySequence(Qt.Key_Up), self, activated=self.previous_sound)
QShortcut(QKeySequence(Qt.Key_Down), self, activated=self.next_sound)
def choose_folder(self):
folder = QFileDialog.getExistingDirectory(
self, "Choose Audio Library Folder"
)
if not folder:
return
self.root_folder = folder
self.folder_label.setText(folder)
self.sounds.clear()
self.collapsed_folders.clear()
self.current_path = None
self.open_location_btn.setEnabled(False)
self.copy_path_btn.setEnabled(False)
self.category.blockSignals(True)
self.category.clear()
self.category.addItem("All Categories")
self.category.blockSignals(False)
self.list.clear()
self.status.setText("Scanning audio files...")
self.search.clear()
self.scanner = Scanner(folder)
self.scanner.found.connect(self.add_sound)
self.scanner.finished.connect(self.scan_finished)
self.scanner.start()
def add_sound(self, full_path, relative, category):
self.sounds.append({
"path": full_path,
"relative": relative,
"category": category,
})
def scan_finished(self, count):
categories = sorted({s["category"] for s in self.sounds}, key=str.lower)
self.category.blockSignals(True)
self.category.clear()
self.category.addItem("All Categories")
self.category.addItems(categories)
self.category.blockSignals(False)
self.sounds.sort(key=lambda x: x["relative"].lower())
self.refresh_list()
self.status.setText(f"Ready — scanned {count:,} audio files.")
def refresh_list(self):
if not hasattr(self, "list"):
return
query = self.search.text().strip().lower()
selected_category = self.category.currentText()
self.list.blockSignals(True)
self.list.clear()
self.visible_sounds = []
shown = 0
current_folder = None
for sound in self.sounds:
if selected_category != "All Categories" and sound["category"] != selected_category:
continue
if query and query not in sound["relative"].lower():
continue
relative = Path(sound["relative"])
folder = str(relative.parent)
# Keep the root-level files together under a clear heading.
if folder == ".":
folder = "Root"
if folder != current_folder:
current_folder = folder
heading = QListWidgetItem(
f"{'▶' if folder in self.collapsed_folders else '▼'} 📁 {folder}"
)
heading.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
heading.setData(Qt.UserRole, None)
heading.setData(Qt.UserRole + 1, folder)
heading.setToolTip("Click to collapse/expand this folder")
self.list.addItem(heading)
if folder in self.collapsed_folders:
continue
item = QListWidgetItem(f"▶ {relative.name}")
item.setToolTip(sound["relative"])
item.setData(Qt.UserRole, sound["path"])
item.setData(Qt.UserRole + 1, folder)
self.list.addItem(item)
self.visible_sounds.append(sound)
shown += 1
self.list.blockSignals(False)
self.count_label.setText(f"{shown:,} sounds")
if shown == 0:
self.current_path = None
self.name_label.setText("No sounds found")
self.path_label.setText("")
self.open_location_btn.setEnabled(False)
self.copy_path_btn.setEnabled(False)
def list_item_clicked(self, item):
if not item:
return
path = item.data(Qt.UserRole)
# Folder heading: toggle collapse/expand.
if not path:
folder = item.data(Qt.UserRole + 1)
if folder:
if folder in self.collapsed_folders:
self.collapsed_folders.remove(folder)
else:
self.collapsed_folders.add(folder)
self.refresh_list()
return
def selection_changed(self, row):
if row < 0:
return
item = self.list.item(row)
if not item:
return
path = item.data(Qt.UserRole)
# Folder heading — clear file actions.
if not path:
self.current_path = None
self.name_label.setText("Select a sound")
self.path_label.setText("")
self.open_location_btn.setEnabled(False)
self.copy_path_btn.setEnabled(False)
return
self.current_path = path
self.open_location_btn.setEnabled(True)
self.copy_path_btn.setEnabled(True)
self.name_label.setText(Path(path).name)
try:
rel = str(Path(path).relative_to(self.root_folder))
except Exception:
rel = path
self.path_label.setText(rel)
def play_selected(self):
item = self.list.currentItem()
if not item:
return
path = item.data(Qt.UserRole)
# Folder heading — nothing to play.
if not path:
return
self.current_path = path
self.open_location_btn.setEnabled(True)
self.copy_path_btn.setEnabled(True)
try:
pygame.mixer.music.load(path)
pygame.mixer.music.play()
self.play_btn.setText("❚❚ Pause")
self.status.setText(f"Playing: {Path(path).name}")
except Exception as e:
QMessageBox.warning(
self,
"Can't play this file",
f"Could not play:\n{path}\n\n{e}"
)
def toggle_play(self):
if not self.current_path:
self.play_selected()
return
if pygame.mixer.music.get_busy():
pygame.mixer.music.pause()
self.play_btn.setText("▶ Resume")
else:
# pygame cannot reliably tell whether the track is paused,
# so restart if no channel is active.
self.play_selected()
def stop(self):
pygame.mixer.music.stop()
self.play_btn.setText("▶ Play")
def previous_sound(self):
row = self.list.currentRow()
while row > 0:
row -= 1
item = self.list.item(row)
if item and item.data(Qt.UserRole):
self.list.setCurrentRow(row)
self.play_selected()
return
def next_sound(self):
row = self.list.currentRow()
while row < self.list.count() - 1:
row += 1
item = self.list.item(row)
if item and item.data(Qt.UserRole):
self.list.setCurrentRow(row)
self.play_selected()
return
def collapse_all(self):
# Collapse every currently visible folder.
folders = set()
for sound in self.sounds:
relative = Path(sound["relative"])
folder = str(relative.parent)
if folder == ".":
folder = "Root"
folders.add(folder)
self.collapsed_folders = folders
self.refresh_list()
def expand_all(self):
self.collapsed_folders.clear()
self.refresh_list()
def open_location(self):
if not self.current_path:
return
path = Path(self.current_path)
try:
if sys.platform.startswith("win"):
os.startfile(path.parent)
elif sys.platform == "darwin":
os.system(f'open "{path.parent}"')
else:
os.system(f'xdg-open "{path.parent}"')
except Exception as e:
QMessageBox.warning(
self,
"Can't open location",
f"Could not open:\n{path.parent}\n\n{e}"
)
def copy_path(self):
if not self.current_path:
return
QApplication.clipboard().setText(str(Path(self.current_path).resolve()))
self.status.setText("Copied full file path to clipboard.")
def set_volume(self, value):
pygame.mixer.music.set_volume(value / 100.0)
def closeEvent(self, event):
try:
pygame.mixer.music.stop()
pygame.mixer.quit()
finally:
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setApplicationName("Audio Library Browser")
window = AudioLibrary()
window.show()
sys.exit(app.exec())