QT读取音频文件并绘制图像
时间: 2024-05-03 19:22:26 浏览: 101
QT 实现文件的读取操作
4星 · 用户满意度95%
以下是使用Python和Qt读取音频文件并绘制波形图像的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt, QFile, QIODevice
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Waveform Viewer')
self.setGeometry(100, 100, 800, 600)
# create a menu bar
menubar = self.menuBar()
file_menu = menubar.addMenu('File')
# add open file action
open_file = file_menu.addAction('Open')
open_file.triggered.connect(self.open_file_dialog)
# initialize variables
self.filename = None
self.audio_data = None
def open_file_dialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.filename, _ = QFileDialog.getOpenFileName(self, "Open Audio File", "", "WAV Files (*.wav)", options=options)
if self.filename:
self.load_audio_data()
self.update()
def load_audio_data(self):
fs, data = wavfile.read(self.filename)
if len(data.shape) > 1:
data = data[:,0] # extract the first channel
self.audio_data = data / 32768.0 # normalize the data to [-1,1]
def paintEvent(self, event):
if self.audio_data is not None:
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
pen = QPen(Qt.black, 1, Qt.SolidLine)
painter.setPen(pen)
x_scale = self.width() / len(self.audio_data)
y_scale = self.height() / 2
x = 0
y = self.height() / 2 + self.audio_data[0] * y_scale
for i in range(1, len(self.audio_data)):
x1 = x + x_scale
y1 = self.height() / 2 + self.audio_data[i] * y_scale
painter.drawLine(x, y, x1, y1)
x, y = x1, y1
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
```
该代码使用了PyQt5库来创建GUI窗口和菜单,并使用matplotlib和scipy库来读取和处理音频数据。在打开文件后,将音频数据绘制为波形图像。波形图像的绘制使用QPainter类的drawLine方法,将每个样本的值连接起来。通过调整x_scale和y_scale变量,可以调整波形图像的大小和比例。
阅读全文