Here is a series of modifications that will allow for multiple songs from any one folder to be selected to play, limiting formats to eliminate user seeing hidden files or choosing non-audio files. Please let me know if this was an appropriate post and critique my code - harshly but thoroughly if you do. I am a beginner... And my first post here @ S.O. In python3.x:
#-*- coding: utf-8 -*-
from threading import Thread
from pyaudio import PyAudio
from pydub import *
from pydub.utils import make_chunks
from tkinter.filedialog import askopenfilenames
from tkinter import Tk
import time
class Song(Thread):
def __init__(self, f, *args, **kwargs):
self.seg = AudioSegment.from_file(f)
self.__is_paused = True
self.p = PyAudio()
print(self.seg.frame_rate)
Thread.__init__(self, *args, **kwargs)
self.start()
def pause(self):
self.__is_paused = True
def play(self):
self.__is_paused = False
def __get_stream(self):
return self.p.open(format=self.p.get_format_from_width(self.seg.sample_width),
channels=self.seg.channels,
rate=self.seg.frame_rate,
output=True)
def run(self):
stream = self.__get_stream()
chunk_count = 0
chunks = make_chunks(self.seg, 100)
while chunk_count < len(chunks) and not self.__is_paused:
data = (chunks[chunk_count])._data
chunk_count += 1
stream.write(data)
stream.stop_stream()
self.p.terminate()
Tk().withdraw()
filename = askopenfilenames(initialdir='/default/path', title="choose your file(s)",
filetypes=(("audio files", "*.flac *.wav *.mp3 *.ogg"), ("none", "")))
# with this logic there is a short gap b/w files - os time to process,
# trying to shorten gap by removing
# 1 second from sleep time... works ok but will be system status
# dependent and may not work across runs??
# Better would be to kill each tread when self._is_paused = True.
# I have a bunch of active threads piling up
for a in filename:
song = Song(a)
song.play()
songLength = song.seg.duration_seconds
time.sleep(songLength - 1)