以前,我用这种方式确定音频文件的长度:
import datetime, mutagen
path = 'C:/Users/User/Desktop/music/13.Numb.mp3'
audiofile = mutagen.File(path)
length = str(datetime.timedelta(seconds = audiofile.info.length))
print(length)
之后,将数字写入数据库。
该代码确实有效,但是当我需要在我的应用程序中使用此信息时,我遇到了问题。
第一个问题:
我的应用程序播放音乐作品。为了确定已经播放了多少秒,还有多少秒要播放,我在 中定义了声源的持续时间QMediaPlayer。非常简化,源持续时间输出如下所示:
from PyQt5 import QtCore, QtWidgets, QtGui, QtMultimedia
import time
class MyWindow(QtWidgets.QWidget):
def __init__(self, parent = None):
super().__init__(parent)
self.play_pause = True
self.song = 'C:/Users/User/Desktop/music/13.Numb.mp3'
self.player = QtMultimedia.QMediaPlayer()
box = QtWidgets.QVBoxLayout(self)
play_btn = QtWidgets.QPushButton('Play', clicked = self.play)
box.addWidget(play_btn)
self.length = QtWidgets.QLabel('Length - 00:00', alignment = QtCore.Qt.AlignCenter)
box.addWidget(self.length)
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.play_mode)
self.timer.start(1000)
def play(self):
if self.play_pause == True:
self.play_pause = False
self.player.setMedia(QtMultimedia.QMediaContent(QtCore.QUrl(self.song)))
self.player.play()
def play_mode(self):
if self.play_pause == False:
self.length.setText(time.strftime('%M:%S', time.localtime(self.player.duration() / 1000)))
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.setWindowTitle(' ')
window.show()
sys.exit(app.exec_())
事实证明,第一个和第二个代码中的数据不同。有时差异可以达到几秒钟。对我来说,这非常重要,所以我想立即使用 Qt 确定并保存轨道的长度。不幸的是,如果不将音频文件添加到QMediaPlayer.
第二个问题:
现在长度以四位数字存储。两位数字分配给分钟,另外两位分配给秒。它看起来像这样: 00: 00
几乎任何一首歌都不到十分钟。那些。在大多数情况下,分钟部分不需要第二个数字。如果不需要第四位数字,我想修剪第一个零。那些。有时字符串应如下所示:0:00。
请告诉我我该怎么做?
таймеры你不需要任何time