跳至正文
View Categories

1 min read

主要内容 #

  • 文件夹读取模块

1. 文件夹读取模块 #

该模块的功能是读取指定文件夹下的所有音乐文件
并存储到指定变量中,然后在界面中展示音乐列表。

以下程序完成了读取文件夹并且显示在界面上的功能:

    def show_music_list(self):
        """
        显示文件夹中所有音乐
        """
        self.qlist.clear() # 将之前的音乐列表清空
        for song in os.listdir(self.cur_path): # 循环指定文件夹下的所有文件
            if song.split('.')[-1] in self.song_formats: # 判断是否符合音乐文件的后缀
                self.songs_list.append([song, os.path.join(
                    self.cur_path, song).replace('\\', '/')]) # 路径中的符号替换
                self.qlist.addItem(song) # 全路径下的音乐文件加入到列表中,列表存储歌曲文件名和全路径
        self.qlist.setCurrentRow(0) # 设置当前行数是第0个,也就是列表中的第一个
        if self.songs_list:
            self.cur_playing_song = self.songs_list[self.qlist.currentRow(
            )][-1] # 设置设定好的当前歌曲

    def set_cur_playing(self):
        """
        设置当前播放的音乐
        """
        self.cur_playing_song = self.songs_list[self.qlist.currentRow()][-1]
        self.player.setMedia(QMediaContent(QUrl(self.cur_playing_song)))
		
	def open_dir(self):
		"""
		打开文件夹
		"""
		self.cur_path = QFileDialog.getExistingDirectory(
			self, "选取文件夹", self.cur_path) # 弹出文件夹选项,手工设置指定文件夹,并且获取对应路径
		if self.cur_path:
			self.show_music_list() # 遍历文件夹下所有文件,将其中的音乐文件存储到qlist中
			# 如下是播放器启动时的设置
			self.cur_playing_song = ''
			self.set_cur_playing() # 获取当前播放音乐
			self.time_slider_1.setText('00:00') # 播放时长设置0
			self.time_slider_2.setText('00:00') # 总时长设置为0
			self.play_slider.setSliderPosition(0) # 播放滑动条置放在起始位置
			self.is_pause = True # 默认暂停播放
			self.play_button.setText('播放') # 将播放键按钮文字设置为播放

完成该功能后,需要设计一个按钮,并将该按钮与上述功能进行连接。
即点击按钮,就可以打开指定文件夹。

以下程序实现按钮与功能的连接(即信号传递)

    # 在self.init()中找到如下这部分代码
	# --打开文件夹按钮
	self.open_button = QPushButton('打开文件夹', self) # 打开文件夹按钮

    # 并且在下一行增加如下这段代码
	self.open_button.clicked.connect(self.open_dir)

将以上所有代码加入到MusicPlayer类中,并且在self.init()函数中做好相应的修改
运行代码,查看具体效果。

2. 小结 #

  • 本章完成了读取文件夹,获取所有音乐文件,并且保存到列表中,最后展示在界面上。

习题 #