python播放歌曲_音频-在python上播放mp3歌曲

黎曾笑
2023-12-01

在这一点上,为什么不提及libasound2-dev:

GitHub:[https://github.com/tuffy/python-audio-tools]

docs:[http://audiotools.sourceforge.net/programming/audiotools.html?highlight=seek#module-audiotools]

这是我发现的最佳解决方案。

(我需要在Raspbian上安装libasound2-dev)

代码摘录大致基于以下内容:

[https://github.com/tuffy/python-audio-tools/blob/master/trackplay]

#!/usr/bin/python

import os

import re

import audiotools.player

START = 0

INDEX = 0

PATH = '/path/to/your/mp3/folder'

class TracklistPlayer:

def __init__(self,

tr_list,

audio_output=audiotools.player.open_output('ALSA'),

replay_gain=audiotools.player.RG_NO_REPLAYGAIN,

skip=False):

if skip:

return

self.track_index = INDEX + START - 1

if self.track_index < -1:

print('--> [track index was negative]')

self.track_index = self.track_index + len(tr_list)

self.track_list = tr_list

self.player = audiotools.player.Player(

audio_output,

replay_gain,

self.play_track)

self.play_track(True, False)

def play_track(self, forward=True, not_1st_track=True):

try:

if forward:

self.track_index += 1

else:

self.track_index -= 1

current_track = self.track_list[self.track_index]

audio_file = audiotools.open(current_track)

self.player.open(audio_file)

self.player.play()

print('--> index: ' + str(self.track_index))

print('--> PLAYING: ' + audio_file.filename)

if not_1st_track:

pass # here I needed to do something :)

if forward:

pass # ... and also here

except IndexError:

print('\n--> playing finished\n')

def toggle_play_pause(self):

self.player.toggle_play_pause()

def stop(self):

self.player.stop()

def close(self):

self.player.stop()

self.player.close()

def natural_key(el):

"""See http://www.codinghorror.com/blog/archives/001018.html"""

return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)]

def natural_cmp(a, b):

return cmp(natural_key(a), natural_key(b))

if __name__ == "__main__":

print('--> path: ' + PATH)

# remove hidden files (i.e. ".thumb")

raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH))

# mp3 and wav files only list

file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list)

# natural order sorting

file_list.sort(key=natural_key, reverse=False)

track_list = []

for f in file_list:

track_list.append(os.path.join(PATH, f))

TracklistPlayer(track_list)

 类似资料: