[Python] 纯文本查看 复制代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import json
import os
import platform
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Optional
from PIL import Image, ImageDraw, ImageFont
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QRectF, QEvent
from PyQt6.QtGui import (
QPixmap,
QWheelEvent,
QMouseEvent,
QPainter,
QIcon,
QDragEnterEvent,
QDragMoveEvent,
QDragLeaveEvent,
QDropEvent,
)
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QPushButton,
QLabel,
QFileDialog,
QMessageBox,
QGraphicsView,
QGraphicsScene,
QGraphicsPixmapItem,
)
os.environ["PYTHONIOENCODING"] = "utf-8"
CREATE_NO_WINDOW = 0x08000000 if os.name == "nt" else 0
# ================= 配置区 =================
SPECTRUM_WIDTH = 3840
SPECTRUM_HEIGHT = 2160
INFO_BAR_HEIGHT = 80
ZOOM_FACTOR = 1.15
MIN_SCALE = 0.05
MAX_SCALE = 20.0
SPEK_FILTER = (
f"showspectrumpic=s={SPECTRUM_WIDTH}x{SPECTRUM_HEIGHT}"
f":mode=combined:scale=log:win_func=hann"
f":saturation=2:color=rainbow"
)
AUDIO_EXTS = {".mp3", ".wav", ".flac", ".ogg", ".aac", ".m4a", ".wma"}
# ================= Windows 拖拽权限 =================
def enable_drag_drop_privilege(hwnd: int):
if os.name != "nt":
return
try:
import ctypes
user32 = ctypes.windll.user32
for msg in (0x0233, 0x004A, 0x0049):
user32.ChangeWindowMessageFilterEx(hwnd, msg, 1, None)
except Exception:
pass
def find_ff_tool(tool_name: str) -> Optional[str]:
path = shutil.which(tool_name)
if path:
return path
system = platform.system()
candidates = []
if system == "Windows":
candidates = [
rf"c:\ffmpeg\bin\{tool_name}.exe",
rf"c:\Program Files\ffmpeg\bin\{tool_name}.exe",
rf"c:\tools\ffmpeg\bin\{tool_name}.exe",
]
elif system == "Darwin":
candidates = [f"/opt/homebrew/bin/{tool_name}", f"/usr/local/bin/{tool_name}"]
else:
candidates = [f"/usr/bin/{tool_name}", f"/usr/local/bin/{tool_name}"]
for p in candidates:
if os.path.isfile(p):
return p
return None
def get_font(size: int = 28) -> ImageFont.FreeTypeFont:
font_candidates = [
"msyh.ttc",
"Microsoft YaHei.ttf",
"PingFang.ttc",
"STHeiti Light.ttc",
"NotoSansCJK-Regular.ttc",
"WenQuanYiMicroHei.ttf",
"DroidSansFallbackFull.ttf",
"arial.ttf",
"DejaVuSans.ttf",
]
for name in font_candidates:
try:
return ImageFont.truetype(name, size)
except (OSError, IOError):
continue
try:
return ImageFont.load_default(size=size)
except TypeError:
return ImageFont.load_default()
def get_valid_audio_path_from_urls(urls) -> Optional[str]:
"""从 URL 列表中提取有效的音频文件路径"""
for url in urls:
path = url.toLocalFile()
if not path:
raw = url.toString()
if raw.startswith("file:///"):
path = raw[8:]
elif raw.startswith("file://"):
path = raw[7:]
if path:
if (
os.name == "nt"
and len(path) >= 3
and path[0] == "/"
and path[2] == ":"
):
path = path[1:]
path = path.replace("/", os.sep)
if path:
path = os.path.normpath(path)
try:
if os.path.isfile(path) and Path(path).suffix.lower() in AUDIO_EXTS:
return path
except (OSError, ValueError):
continue
return None
FFMPEG_PATH = find_ff_tool("ffmpeg")
FFPROBE_PATH = find_ff_tool("ffprobe")
class SpectrumGraphicsView(QGraphicsView):
"""支持滚轮缩放、拖拽平移、窗口自适应的图形视图(不处理拖拽)"""
def __init__(self, parent=None):
super().__init__(parent)
self._scene = QGraphicsScene(self)
self.setScene(self._scene)
self.setAcceptDrops(False)
self.viewport().setAcceptDrops(False)
self.setRenderHint(QPainter.RenderHint.Antialiasing)
self.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setBackgroundBrush(Qt.GlobalColor.black)
self.setDragMode(QGraphicsView.DragMode.NoDrag)
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
self._pixmap_item: Optional[QGraphicsPixmapItem] = None
self._current_scale: float = 1.0
self._fit_scale: float = 1.0
self._user_zoomed: bool = False
self._drag_over = False
self._mouse_pressed = False
self._last_mouse_pos = None
self.viewport().installEventFilter(self)
def set_drag_over(self, state: bool):
"""由 MainWindow 调用,控制拖拽视觉反馈"""
self._drag_over = state
self.viewport().update()
def eventFilter(self, watched, event):
if watched is not self.viewport():
return super().eventFilter(watched, event)
etype = event.type()
if etype == QEvent.Type.MouseButtonPress:
if event.button() == Qt.MouseButton.LeftButton and self._pixmap_item:
self._mouse_pressed = True
self._last_mouse_pos = event.position().toPoint()
self.viewport().setCursor(Qt.CursorShape.ClosedHandCursor)
return True
elif etype == QEvent.Type.MouseMove:
if (
self._mouse_pressed
and self._last_mouse_pos is not None
and self._pixmap_item
):
delta = event.position().toPoint() - self._last_mouse_pos
self.horizontalScrollBar().setValue(
self.horizontalScrollBar().value() - delta.x()
)
self.verticalScrollBar().setValue(
self.verticalScrollBar().value() - delta.y()
)
self._last_mouse_pos = event.position().toPoint()
return True
elif etype == QEvent.Type.MouseButtonRelease:
if event.button() == Qt.MouseButton.LeftButton:
self._mouse_pressed = False
self._last_mouse_pos = None
self.viewport().setCursor(Qt.CursorShape.ArrowCursor)
return True
return super().eventFilter(watched, event)
# ===================== 图片加载与视图控制 =====================
def load_spectrum_image(self, img_path: str) -> bool:
self._scene.clear()
self.resetTransform()
self._user_zoomed = False
self._pixmap_item = None
pix = QPixmap(img_path)
if pix.isNull():
return False
self._pixmap_item = QGraphicsPixmapItem(pix)
self._scene.addItem(self._pixmap_item)
self._scene.setSceneRect(self._pixmap_item.boundingRect())
self._fit_to_view()
return True
def _fit_to_view(self):
if not self._pixmap_item:
return
self.fitInView(self._pixmap_item, Qt.AspectRatioMode.KeepAspectRatio)
self._fit_scale = self.transform().m11()
self._current_scale = self._fit_scale
def resizeEvent(self, event):
super().resizeEvent(event)
if self._pixmap_item and not self._user_zoomed:
QApplication.processEvents()
self._fit_to_view()
def wheelEvent(self, event: QWheelEvent):
if not self._pixmap_item:
return super().wheelEvent(event)
factor = ZOOM_FACTOR if event.angleDelta().y() > 0 else 1 / ZOOM_FACTOR
new_scale = self._current_scale * factor
if MIN_SCALE <= new_scale <= MAX_SCALE:
self.scale(factor, factor)
self._current_scale = new_scale
self._user_zoomed = True
def mouseDoubleClickEvent(self, event: QMouseEvent):
if self._pixmap_item:
self._user_zoomed = False
self._fit_to_view()
super().mouseDoubleClickEvent(event)
# ===================== 拖拽视觉反馈 =====================
def drawForeground(self, painter: QPainter, rect):
super().drawForeground(painter, rect)
if self._drag_over:
painter.save()
vp_rect = self.viewport().rect()
top_left = self.mapToScene(vp_rect.topLeft())
bottom_right = self.mapToScene(vp_rect.bottomRight())
mapped_rect = QRectF(top_left, bottom_right)
pen = painter.pen()
pen.setColor(Qt.GlobalColor.cyan)
pen.setWidth(3)
pen.setStyle(Qt.PenStyle.DashLine)
painter.setPen(pen)
painter.drawRect(mapped_rect.adjusted(2, 2, -2, -2))
painter.setPen(Qt.GlobalColor.white)
font = painter.font()
font.setPointSize(16)
painter.setFont(font)
painter.drawText(
mapped_rect, Qt.AlignmentFlag.AlignCenter, "🎵 释放音频文件以生成频谱"
)
painter.restore()
# ================= 辅助功能 =================
def extract_audio_info(audio_path: str) -> dict:
if not FFPROBE_PATH or not os.path.exists(audio_path):
return {}
cmd = [
FFPROBE_PATH,
"-v",
"quiet",
"-print_format",
"json",
"-show_streams",
"-select_streams",
"a:0",
"-show_format",
audio_path,
]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30,
encoding="utf-8",
errors="replace",
creationflags=CREATE_NO_WINDOW,
)
if result.returncode != 0:
return {}
data = json.loads(result.stdout)
streams = data.get("streams")
if not streams:
return {}
stream = streams[0]
fmt = data.get("format", {})
duration = float(fmt.get("duration", 0))
h, rem = divmod(int(duration), 3600)
m, s = divmod(rem, 60)
bitrate = int(stream.get("bit_rate", 0)) // 1000
return {
"filename": Path(audio_path).name,
"codec": stream.get("codec_name", "未知"),
"sample_rate": f"{stream.get('sample_rate', '0')} Hz",
"channels": "立体声" if int(stream.get("channels", 2)) == 2 else "单声道",
"bit_rate": f"{bitrate} kb/s" if bitrate > 0 else "未知",
"duration": f"{h:02d}:{m:02d}:{s:02d}",
}
except Exception:
return {}
def draw_info_bar(spectrum_path: str, info: dict, output_path: str) -> bool:
if not os.path.exists(spectrum_path) or not info:
return False
try:
img = Image.open(spectrum_path).convert("RGBA")
w, h = img.size
canvas = Image.new("RGBA", (w, h + INFO_BAR_HEIGHT), (0, 0, 0, 255))
canvas.paste(img, (0, INFO_BAR_HEIGHT))
draw = ImageDraw.Draw(canvas)
draw.rectangle([0, 0, w, INFO_BAR_HEIGHT], fill=(20, 20, 20, 230))
font = get_font(28)
text = (
f"文件: {info['filename']} | 时长: {info['duration']} | "
f"编码: {info['codec']} | 采样率: {info['sample_rate']} | "
f"声道: {info['channels']} | 比特率: {info['bit_rate']}"
)
bbox = draw.textbbox((0, 0), text, font=font)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
x = max(10, (w - tw) // 2)
y = (INFO_BAR_HEIGHT - th) // 2
draw.text((x, y), text, font=font, fill=(255, 255, 255, 255))
canvas.convert("RGB").save(output_path, "PNG", optimize=True)
return True
except Exception:
return False
def sanitize_filename(name: str) -> str:
safe = "".join(c for c in name if c.isascii() and c not in r'<>:"/\|?*').strip()
return safe or "audio"
# ================= 工作线程 =================
class SpectrumWorker(QThread):
finished = pyqtSignal(str, str)
def __init__(self, audio_path: str, cache_dir: str):
super().__init__()
self.audio_path = audio_path
self.cache_dir = cache_dir
self._tmp_dir: Optional[str] = None
self._stopped = False
def stop(self):
self._stopped = True
def run(self):
if not FFMPEG_PATH or not FFPROBE_PATH:
self.finished.emit("", "未找到 ffmpeg/ffprobe,请安装并加入 PATH")
return
try:
info = extract_audio_info(self.audio_path)
if not info:
self.finished.emit("", "无法提取音频信息,请确认文件有效")
return
raw_path = self._generate_spectrum()
if self._stopped or not raw_path:
self.finished.emit("", "频谱生成失败或已取消")
return
stem = sanitize_filename(Path(self.audio_path).stem)
final_path = os.path.join(self.cache_dir, f"{stem}_full.png")
if draw_info_bar(raw_path, info, final_path):
self.finished.emit(final_path, "")
else:
self.finished.emit("", "信息栏绘制失败")
except Exception as e:
self.finished.emit("", f"处理异常: {e}")
finally:
self._cleanup()
def _generate_spectrum(self) -> Optional[str]:
self._tmp_dir = tempfile.mkdtemp(prefix="spectrum_")
stem = sanitize_filename(Path(self.audio_path).stem)
out = os.path.join(self._tmp_dir, f"{stem}_raw.png")
cmd = [
FFMPEG_PATH,
"-y",
"-i",
self.audio_path,
"-filter_complex",
SPEK_FILTER,
"-frames:v",
"1",
out,
]
try:
r = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=600,
encoding="utf-8",
errors="replace",
creationflags=CREATE_NO_WINDOW,
)
if (
r.returncode == 0
and os.path.exists(out)
and os.path.getsize(out) > 1000
):
return out
except subprocess.TimeoutExpired:
pass
except Exception:
pass
return None
def _cleanup(self):
if self._tmp_dir and os.path.isdir(self._tmp_dir):
try:
shutil.rmtree(self._tmp_dir, ignore_errors=True)
except Exception:
pass
# ========================= 主窗口 =========================
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("音频频谱图查看器")
self.resize(1800, 1100)
self.setAcceptDrops(True)
self._current_image: Optional[str] = None
self._current_song: Optional[str] = None
self._worker: Optional[SpectrumWorker] = None
self._cache_dir = os.path.join(tempfile.gettempdir(), "spectrum_viewer_cache")
os.makedirs(self._cache_dir, exist_ok=True)
central = QWidget()
self.setCentralWidget(central)
layout = QVBoxLayout(central)
layout.setContentsMargins(10, 10, 10, 10)
btn_layout = QHBoxLayout()
style = (
"QPushButton { padding: 10px 20px; background: #1E90FF; color: white; "
"border-radius: 4px; font-size: 14px; } "
"QPushButton:hover { background: #4682B4; } "
"QPushButton:disabled { background: #5F9EA0; color: #A9A9A9; }"
)
self.btn_open = QPushButton("📂 打开音频文件")
self.btn_save = QPushButton("💾 保存频谱图")
self.btn_save.setEnabled(False)
self.btn_open.setStyleSheet(style)
self.btn_save.setStyleSheet(style)
self.lbl_status = QLabel("就绪")
self.lbl_status.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.lbl_status.setStyleSheet("color: #aaa; font-size: 13px;")
btn_layout.addWidget(self.btn_open)
btn_layout.addWidget(self.btn_save)
btn_layout.addStretch()
btn_layout.addWidget(self.lbl_status)
layout.addLayout(btn_layout)
self.view = SpectrumGraphicsView()
self.view.setMinimumSize(1280, 640)
layout.addWidget(self.view, stretch=1)
self.btn_open.clicked.connect(self._open_file)
self.btn_save.clicked.connect(self._save_spectrum)
if not FFMPEG_PATH or not FFPROBE_PATH:
self.lbl_status.setText("⚠️ 未检测到 ffmpeg/ffprobe")
self.lbl_status.setStyleSheet("color: #ff6b6b; font-size: 13px;")
# ===================== 拖拽事件(在 MainWindow 层处理) =====================
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
path = get_valid_audio_path_from_urls(event.mimeData().urls())
if path:
event.acceptProposedAction()
self.view.set_drag_over(True)
return
event.ignore()
def dragMoveEvent(self, event: QDragMoveEvent):
if event.mimeData().hasUrls():
path = get_valid_audio_path_from_urls(event.mimeData().urls())
if path:
event.acceptProposedAction()
return
event.ignore()
def dragLeaveEvent(self, event: QDragLeaveEvent):
self.view.set_drag_over(False)
super().dragLeaveEvent(event)
def dropEvent(self, event: QDropEvent):
self.view.set_drag_over(False)
if event.mimeData().hasUrls():
path = get_valid_audio_path_from_urls(event.mimeData().urls())
if path:
event.acceptProposedAction()
self._handle_dropped_file(path)
return
event.ignore()
# ===================== 窗口事件 =====================
def showEvent(self, event):
super().showEvent(event)
if os.name == "nt":
enable_drag_drop_privilege(int(self.winId()))
def closeEvent(self, event):
if self._worker and self._worker.isRunning():
self._worker.stop()
self._worker.wait(3000)
if os.path.isdir(self._cache_dir):
shutil.rmtree(self._cache_dir, ignore_errors=True)
super().closeEvent(event)
# ===================== 文件处理 =====================
def _open_file(self):
if self._worker and self._worker.isRunning():
self._worker.stop()
self._worker.wait()
path, _ = QFileDialog.getOpenFileName(
self,
"选择音频文件",
"",
"Audio Files (*.mp3 *.wav *.flac *.ogg *.aac *.m4a *.wma)",
)
if path:
self._start_processing(path)
def _handle_dropped_file(self, path: str):
if not os.path.isfile(path):
return
if self._worker and self._worker.isRunning():
self._worker.stop()
self._worker.wait()
self._start_processing(path)
def _start_processing(self, path: str):
self.btn_open.setEnabled(False)
self.btn_save.setEnabled(False)
self.view._scene.clear()
self.view._pixmap_item = None
self._current_image = None
self._current_song = Path(path).stem
self.lbl_status.setText(f"⏳ 正在处理: {self._current_song} ...")
self.lbl_status.setStyleSheet("color: #ffd93d; font-size: 13px;")
self._worker = SpectrumWorker(path, self._cache_dir)
self._worker.finished.connect(self._on_ready)
self._worker.start()
def _on_ready(self, image_path: str, error: str):
self.btn_open.setEnabled(True)
if error:
QMessageBox.critical(self, "错误", error)
self.lbl_status.setText("❌ 处理失败")
self.lbl_status.setStyleSheet("color: #ff6b6b; font-size: 13px;")
return
self._current_image = image_path
if self.view.load_spectrum_image(image_path):
self.btn_save.setEnabled(True)
self.lbl_status.setText(f"✅ 已完成: {self._current_song}")
self.lbl_status.setStyleSheet("color: #6bff8e; font-size: 13px;")
else:
QMessageBox.critical(self, "错误", "频谱图加载失败")
self.lbl_status.setText("❌ 图片加载失败")
def _save_spectrum(self):
if not self._current_image:
return
default = f"{self._current_song}_spectrum.png"
path, _ = QFileDialog.getSaveFileName(
self, "保存频谱图", default, "PNG (*.png)"
)
if path:
try:
shutil.copy2(self._current_image, path)
QMessageBox.information(self, "成功", f"已保存至:\n{path}")
except Exception as e:
QMessageBox.critical(self, "保存失败", str(e))
def main():
app = QApplication(sys.argv)
app.setStyle("Fusion")
if getattr(sys, "frozen", False):
base = Path(sys.executable).parent
else:
base = Path(__file__).resolve().parent
icon_path = base / "color.ico"
if icon_path.exists():
app.setWindowIcon(QIcon(str(icon_path)))
win = MainWindow()
win.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()