Preface:

Make a simple music player in Python. Let’s have fun

The development tools

**Python version: **3.6.4

Related modules:

Pyqt5 module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required related modules.

Introduction of the principle

In fact, the relevant files in the source code I have made some annotations, pyQT5 will basically look at the source code to understand, because the principle is still very simple. Here is a brief introduction.

Design interface

The QAQ interface is simple and looks like this:

The source code defines the elements contained in the interface one by one, and then typeset it:

self.label1 = QLabel('00:00') self.label1.setStyle(QStyleFactory.create('Fusion')) self.label2 = QLabel('00:00') Self.label2. setStyle(qstyleFactory.create ('Fusion')) # -- slider self.slider = q.horizontal (qt.horizontal, self) self.slider.sliderMoved[int].connect(lambda: Self.player.setposition (self.slider.value())) self.slider.setstyle (qstyleFactory.create ('Fusion')) # -- Play button Self. play_button = QPushButton(' play ', self) self.play_button.clicked.connect(self.playMusic) self.play_button.setStyle(QStyleFactory.create('Fusion')) # Self. preview_button = QPushButton(' preview_button ', self) self.preview_button.clicked.connect(self.previewMusic) Self.preview_button. setStyle(qstyleFactory.create ('Fusion')) # self) self.next_button.clicked.connect(self.nextMusic) self.next_button.setStyle(QStyleFactory.create('Fusion')) # Self. open_button = QPushButton(' open folder ', self) self.open_button.setStyle(QStyleFactory.create('Fusion')) self.open_button.clicked.connect(self.openDir) # -- show music list self. Qlist = QListWidget () the self. Qlist. ItemDoubleClicked. Connect (self. DoubleClicked) Self.qlist. setStyle(qstyleFactory.create (' Windows ')) # Self.cmb = QComboBox() self.cmb.setStyle(qstyleFactory.create ('Fusion')) Self.cmb.additem (' 1 ') self.cmb.addItem(' 1 ') # -- timer self.cmb.addItem(' 1 ') self.cmb.addItem(' 1 ') # -- timer self.cmb.addItem(' 1 ') Self. The timer. Start. (1000) the self timer. The timeout. Connect (self. PlayByMode) # interface layout self. The grid = QGridLayout () self.setLayout(self.grid) self.grid.addWidget(self.qlist, 0, 0, 5, 10) self.grid.addWidget(self.label1, 0, 11, 1, 1) self.grid.addWidget(self.slider, 0, 12, 1, 1) self.grid.addWidget(self.label2, 0, 13, 1, 1) self.grid.addWidget(self.play_button, 0, 14, 1, 1) self.grid.addWidget(self.next_button, 1, 11, 1, 2) self.grid.addWidget(self.preview_button, 2, 11, 1, 2) self.grid.addWidget(self.cmb, 3, 11, 1, 2) self.grid.addWidget(self.open_button, 4, 11, 1, 2)Copy the code

Two. Realize the functions of each part

(1) Select the folder for storing music

Call the corresponding pyQt5 function directly:

Def openDir(self): Self. Cur_path = QFileDialog. GetExistingDirectory (self, "select the folder", the self cur_path) if self. Cur_path: self.showMusicList() self.cur_playing_song = '' self.setCurPlaying() self.label1.setText('00:00') Self. Label2. SetText (' 00:00) self. The slider. SetSliderPosition (0) self. Is_pause = True self. Play_button. SetText () 'play'Copy the code

After opening the folder, display all the music files on the left side of the interface and save some necessary information:

Def showMusicList(self): self.qlist.clear() self.updateSetting() 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) if self.songs_list: self.cur_playing_song = self.songs_list[self.qlist.currentRow()][-1]Copy the code

(2) Music playing

QMediaPlayer:

Def playMusic(self): if self.qlist.count() == 0: Self. Tips (' within the current path is playing music files) return if not the self. The player. IsAudioAvailable () : self.setCurPlaying() if self.is_pause or self.is_switching: Self.player.play () self.is_pause = False self.play_button.settext (' pause ') elif (not self.is_pause) and (not self.player.play() self.is_pause = False self.play_button.settext (' pause ' Self.is_switching): self.player.pause() self.is_pause = True self.play_button.settext (' play ')Copy the code

(3) Music switch

Click the previous/next button to switch:

Def previewMusic(self): self.slider.setValue(0) if self.qlist.count() == 0: Return pre_row = self.qlist.currentrow ()-1 if self.qlist.currentrow ()! = 0 else self.qlist.count() - 1 self.qlist.setCurrentRow(pre_row) self.is_switching = True self.setCurPlaying() Self.playmusic () self.is_switching = False "" def nextMusic(self): self.playmusic () self.is_switching = False self.slider.setValue(0) if self.qlist.count() == 0: Return next_row = self.qlist.currentrow ()+1 if self.qlist.currentrow ()! = self.qlist.count()-1 else 0 self.qlist.setCurrentRow(next_row) self.is_switching = True self.setCurPlaying() self.playMusic() self.is_switching = FalseCopy the code

Double-click a song to switch:

Def doubleClicked(self): self.slider.setValue(0) self.is_switching = True self.setCurPlaying() self.playMusic() self.is_switching = FalseCopy the code

Switch according to playback mode:

Play music according to play mode
	def playByMode(self) :
		if (not self.is_pause) and (not self.is_switching):
			self.slider.setMinimum(0)
			self.slider.setMaximum(self.player.duration())
			self.slider.setValue(self.slider.value() + 1000)
		self.label1.setText(time.strftime('%M:%S', time.localtime(self.player.position()/1000)))
		self.label2.setText(time.strftime('%M:%S', time.localtime(self.player.duration()/1000)))
		# Order play
		if (self.cmb.currentIndex() == 0) and (not self.is_pause) and (not self.is_switching):
			if self.qlist.count() == 0:
				return
			if self.player.position() == self.player.duration():
				self.nextMusic()
		# Single loop
		elif (self.cmb.currentIndex() == 1) and (not self.is_pause) and (not self.is_switching):
			if self.qlist.count() == 0:
				return
			if self.player.position() == self.player.duration():
				self.is_switching = True
				self.setCurPlaying()
				self.slider.setValue(0)
				self.playMusic()
				self.is_switching = False
		# random play
		elif (self.cmb.currentIndex() == 2) and (not self.is_pause) and (not self.is_switching):
			if self.qlist.count() == 0:
				return
			if self.player.position() == self.player.duration():
				self.is_switching = True
				self.qlist.setCurrentRow(random.randint(0, self.qlist.count()-1))
				self.setCurPlaying()
				self.slider.setValue(0)
				self.playMusic()
				self.is_switching = False
Copy the code

That’s the end of this article, thank you for watching, follow me every day to share a series of Python gadgets, next article to share remote control of your computer using email

To thank you readers, I’d like to share some of my recent programming favorites to give back to each and every one of you in the hope that they can help you.

Click dry goods mainly have access:

① Over 2000 Python ebooks (both mainstream and classic books should be available)

②Python Standard Library (Most Complete Chinese version)

③ project source code (forty or fifty interesting and classic practice projects and source code)

④Python basic introduction, crawler, Web development, big data analysis video (suitable for small white learning)

⑤ A Roadmap for Learning Python

⑥ Two days of Python crawler boot camp live access

All done~ Complete source code + dry plus Python novice learning exchange community: 594356095