潇洒郎: python 使用moviepy 模块开发音视频播放器,实现:播放、暂停、恢复、结束、快进、快退、音量增加、音量减少、倍速播放

 

 

 

 

 

 

 

 

# coding=utf-8
'''
Author: xuxiaosa
Created_Date: 2022/5/24
Created_Time: 14:00
'''
# pip install pycaw moviepy numpy

import os,re
from tkinter import Tk, Label, Button, Menu, StringVar, Entry,  messagebox, filedialog,END

import pygame
import traceback
from moviepy.editor import VideoFileClip
import os, sys, time
import numpy as np
import threading
import ctypes
import comtypes
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

class Image:
    def __init__(self, img_name: str, ratio=0.4):
        """
        img_name: 图片文件名,如'background.jpg'、'ink.png',注意为字符串
        ratio: 图片缩放比例,与主屏幕相适应,默认值为0.4
        """
        self.img_name = img_name
        self.ratio = ratio
        self.image_1080x1920 = pygame.image.load(self.img_name).convert_alpha() #图像转换
        self.img_width = self.image_1080x1920.get_width()
        self.img_height = self.image_1080x1920.get_height()

        self.size_scaled = self.img_width * self.ratio, self.img_height * self.ratio

        self.image_scaled = pygame.transform.smoothscale(self.image_1080x1920, self.size_scaled)
        self.img_width_scaled = self.image_scaled.get_width()
        self.img_height_scaled = self.image_scaled.get_height()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        """
        surface: 图片放置的表面
        center_x, center_y: 图片放置在表面的<中心坐标>
        """
        upperleft_x = center_x - self.img_width_scaled / 2
        upperleft_y = center_y - self.img_height_scaled / 2
        surface.blit(self.image_scaled, (upperleft_x, upperleft_y))

def get_font(fontName_or_fontType, font_size, bold=True, italic=False):
    if '.' not in fontName_or_fontType:
        font = pygame.font.SysFont('华文彩云', size=font_size, bold=bold, italic=italic)
    else:
        font = pygame.font.Font(fontName_or_fontType, size=font_size)
    return font

class Color:
    # 自定义颜色
    ACHIEVEMENT = pygame.Color(220, 160, 87)
    VERSION = pygame.Color(220, 160, 87)
    # 固定颜色
    BLACK = pygame.Color(0, 0, 0)
    WHITE = pygame.Color(255, 255, 255)
    RED = pygame.Color(255, 0, 0)
    GREEN = pygame.Color(0, 255, 0)
    BLUE = pygame.Color(0, 0, 255)
    GREY = pygame.Color(128, 128, 128)  # 中性灰
    TRANSPARENT = pygame.Color(255, 255, 255, 0)  # 白色的完全透明

class Text:
    def __init__(self, text, font_size=25, text_color=Color.BLACK, font_name='华文行楷', bold=True, italic=False):
        """
        text: 文本内容,如'大学生模拟器',注意是字符串形式
        text_color: 字体颜色,如pygame.color.Color('#ffffff') pygame.color.Color(255,2555,255,255)
        font_name: 字体文件(.ttc),'隶书', '幼圆', '华文彩云', '华文仿宋', '华文琥珀', '华文楷体', '华文隶书', '华文宋体', '华文细黑', '华文行楷', '华文新魏', '华文中宋'
        font_size: 字体大小,如20、10
        """
        self.text = text
        self.text_color = text_color
        self.font_name = font_name
        self.font_size = font_size
        font= get_font(self.font_name, font_size, bold=bold, italic=italic)
        self.text_image = font.render(self.text, True, self.text_color).convert_alpha()
        self.text_width = self.text_image.get_width()
        self.text_height = self.text_image.get_height()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        """
        surface: 文本放置的表面
        center_x, center_y: 文本放置在表面的<中心坐标>
        """
        upperleft_x = center_x - self.text_width / 2
        upperleft_y = center_y - self.text_height / 2
        surface.blit(self.text_image, (upperleft_x, upperleft_y))

class ButtonText(Text):
    def __init__(self, text, font_size=25, text_color=Color.BLACK, font_name='timesnewroman', bold=True, italic=False):
        super().__init__(text, font_size, text_color, font_name, bold, italic)
        self.rect = self.text_image.get_rect()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        super().draw(surface, center_x, center_y)
        self.rect.center = center_x, center_y

    def handle_event(self, command, *args):
        self.hovered = self.rect.collidepoint(pygame.mouse.get_pos())
        if self.hovered:
            return command(*args)

class ButtonImage(Image):
    def __init__(self, img_name: str, ratio=0.4):
        super().__init__(img_name, ratio)
        self.rect = self.image_scaled.get_rect()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        super().draw(surface, center_x, center_y)
        self.rect.center = center_x, center_y

    def handle_event(self, command, *args):
        self.hovered = self.rect.collidepoint(pygame.mouse.get_pos())
        if self.hovered:
            return command(*args)

class Player:
    def __init__(self, file_path ,title= "我爱你", width=502, height= 400, icon=None, span= 5):
        # 获取视频片段、时长
        self.videofile = VideoFileClip(file_path)
        self.clip0= self.clip = self.videofile.subclip(0, self.videofile.duration)
        self.play_start=0
        self.play_end= 0
        self.playFlag= threading.Event() # 是否停止播放标志 不可由播放线程控制, 只能主线程控制
        self.playFlag.set()
        self.stopFlag= threading.Event()
        self.pause_time= 0
        self.s_pause_time=0
        self.played_time = 0
        self.th=None
        self.volumex = 0
        self.speedx = 1
        self.span= span

        pygame.display.set_caption(title)
        self.width, self.height = width, height
        self.bottom_magin_ratio = 0.2
        self.left_right_magin_ratio = 0.0001
        self.screen = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)  # pygame.FULLSCREEN全屏 pygame.RESIZABLE可伸缩, pygame.NOFRAME无边框
        # 设置屏幕左上角图标
        # if icon:
        #     game_icon = pygame.image.load(icon)
        #     pygame.display.set_icon(game_icon)
        self.main()

    def main(self):
        self.is_start=False
        is_over=False
        while True:
            if not self.is_start: # 默认播放
                self.played_time = 0
                self.stop()
                self.start()
                self.is_start=True
            if is_over:
                break
            for event in pygame.event.get():
                if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                    pygame.display.quit()
                    self.stop()
                    #pygame.quit()
                    is_over=True
                    #sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                    x, y = event.pos
                    if x < self.screen.get_width() and y < self.screen.get_height() and self.is_start:
                        # 实现点击界面可暂停可播放功能
                        if self.playFlag.isSet(): # 如果在播放中, 则暂停
                            print('暂停中')
                            self.play_end = time.time()
                            self.update_played_time()
                            self.playFlag.clear()
                        else: # 如果在暂停中, 则播放
                            print('播放中')
                            self.play_start=time.time()
                            self.playFlag.set()
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_F1):
                    self.is_start=True
                    self.played_time=0
                    self.stop()
                    self.start()
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_F2):  # 关闭
                    print('停止命令')
                    self.stop()
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT):
                    print('点击右键')
                    if self.playFlag.isSet(): # 播放中
                        self.play_end = time.time()
                        self.update_played_time()
                    self.stop()
                    self.start(self.span)
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT):
                    print('点击左键')
                    if self.playFlag.isSet(): # 播放中
                        self.play_end = time.time()
                        self.update_played_time()
                    self.stop()
                    self.start(self.span, True)
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_UP): # 音量加
                    print('音量+')
                    now_volumn = self.volume()
                    now_volumn += 1
                    if now_volumn < 0:
                        self.volume(0)
                    else:
                        self.volume(now_volumn)
                    # self.volumex += 1
                    # if self.volumex < 0:
                    #     self.volumex = 1
                    # if self.playFlag.isSet():  # 播放中
                    #     self.play_end = time.time()
                    #     self.update_played_time()
                    # self.stop()
                    # self.start(is_volumex=True)
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN): # 音量减
                    print('音量-')
                    now_volumn= self.volume()
                    now_volumn-=1
                    if now_volumn<0:
                        self.volume(0)
                    else:
                        self.volume(now_volumn)
                    # self.volumex -= 1 # clip.fl(lambda gf, t: factor * gf(t), keep_duration=True)
                    # if self.volumex < 0:
                    #     self.volumex = 0
                    # if self.playFlag.isSet():  # 播放中
                    #     self.play_end = time.time()
                    #     self.update_played_time()
                    # self.stop()
                    # self.start(is_volumex=True)
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_EQUALS):
                    print('速度+')
                    self.speedx += 0.1 # clip.fl_time(lambda t: factor * t, apply_to=['mask', 'audio'])加速
                    if self.playFlag.isSet(): # 播放中
                        self.play_end = time.time()
                        self.update_played_time()
                    self.stop()
                    self.start(is_speedx=True)
                if (event.type == pygame.KEYDOWN and event.key == pygame.K_MINUS):
                    print('速度-')
                    self.speedx -= 0.1
                    if self.speedx<0:
                        self.speedx=0.1
                    if self.playFlag.isSet(): # 播放中
                        self.play_end = time.time()
                        self.update_played_time()
                    self.stop()
                    self.start(is_speedx=True)

            pygame.display.update()

    def update_played_time(self):
        sp = self.play_end - self.play_start
        if sp >= 0:
            self.played_time += sp

    def stop(self):
        self.stopFlag.set()
        try:
            # self.clip.close()
            ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.th.ident), ctypes.py_object(SystemExit))
        except:
            print('stop error')

    def _start(self, span, is_back, is_speedx, is_volumex):
        if is_back:
            self.played_time = self.played_time - span
        else:
            self.played_time = self.played_time + span
        if self.played_time >= self.videofile.duration:
            self.played_time = self.videofile.duration - 1
        if self.played_time < 0:
            self.played_time = 0
        print(f'播放 {self.played_time}- {self.videofile.duration}')
        self.clip = self.clip0.subclip(self.played_time, self.videofile.duration)
        if is_speedx:
            print(f'变速: {self.speedx}')
            self.clip = self.clip.speedx(self.speedx)
        if is_volumex:
            print(f'变音量: {self.volumex}')
            self.clip = self.clip.volumex(self.volumex)
        self.playFlag.set()
        self.stopFlag.clear()
        try:
            self.play_start = time.time()
            self.video_play(clip=self.clip, screen=self.screen, playFlag=self.playFlag, stopFlag=self.stopFlag)
            #self.clip.preview(screen=self.screen, playFlag=self.playFlag, stopFlag=self.stopFlag)
        except:
            print('止上')

    def start(self, span=0, is_back=False, is_speedx=False, is_volumex=False):
        self.th = threading.Thread(target=self._start, args=(span, is_back, is_speedx, is_volumex))
        self.th.start()

    def video_play(self, clip, screen=None, playFlag=None, stopFlag=None, fps=15, fullscreen=False):
        if fullscreen:
            flags = pygame.FULLSCREEN
        else:
            flags = 0
        if not screen:
            screen = pygame.display.set_mode(clip.size, flags)
        videoFlag = threading.Event()
        audioFlag = threading.Event()
        threading.Thread(target=self.audio_play, args=(clip.audio, audioFlag, videoFlag, stopFlag)).start()
        img = clip.get_frame(0)
        self.imdisplay(img, screen)
        videoFlag.set()
        audioFlag.wait()
        t0 = time.time()
        for t in np.arange(1.0 / fps, clip.duration - .001, 1.0 / fps):
            if not playFlag.isSet():
                audioFlag.clear()
                playFlag.wait()
                audioFlag.set()
            if stopFlag.isSet():
                audioFlag.clear()
                stopFlag.clear()
                return
            img = clip.get_frame(t)
            t1 = time.time()
            time.sleep(max(0, t - (t1 - t0)))
            self.imdisplay(img, screen)

    def audio_play(self, clip, audioFlag=None, videoFlag=None, stopFlag=None, fps=22050, buffersize=3000, nbytes=2):
        pygame.mixer.quit()  #
        pygame.mixer.init(fps, -8 * nbytes, clip.nchannels, 1024)
        totalsize = int(fps * clip.duration)
        pospos = np.array(list(range(0, totalsize, buffersize)) + [totalsize])
        tt = (1.0 / fps) * np.arange(pospos[0], pospos[1])
        sndarray = clip.to_soundarray(tt, nbytes=nbytes, quantize=True)
        chunk = pygame.sndarray.make_sound(sndarray)
        if (audioFlag is not None) and (videoFlag is not None):
            audioFlag.set()
            videoFlag.wait()
        channel = chunk.play()
        for i in range(1, len(pospos) - 1):
            tt = (1.0 / fps) * np.arange(pospos[i], pospos[i + 1])
            sndarray = clip.to_soundarray(tt, nbytes=nbytes, quantize=True)
            chunk = pygame.sndarray.make_sound(sndarray)
            while channel.get_queue():
                time.sleep(0.003)
                audioFlag.wait()
                if stopFlag is not None:
                    if stopFlag.isSet():
                        channel.stop()
                        del channel
                        return
                if videoFlag is not None:
                    if not videoFlag.is_set():
                        channel.stop()
                        del channel
                        return
            channel.queue(chunk)

    def imdisplay(self, imarray, screen=None):
        a = pygame.surfarray.make_surface(imarray.swapaxes(0, 1))
        _w, _h = a.get_width(), a.get_height()
        width, height = self.screen.get_size()
        _hwratio = _h / _w  # 保持不变,显示不变形
        start_y = 1
        start_x = self.left_right_magin_ratio * width
        w = width * (1 - 2 * self.left_right_magin_ratio)
        h = height * (1 - self.bottom_magin_ratio) - 1
        if _w < w and _h < h:  # 图片大小小于显示区
            _wratio = w / _w  # 图片扩大为原来的>1倍
            _hratio = h / _w
            if _wratio > _hratio:
                _h2 = _h * _hratio
                _w2 = _h2 / _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
            else:
                _w2 = _w * _wratio
                _h2 = _w2 * _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
        elif _w > w and _h > h:  # 图片大于显示区
            _wratio = w / _w  # 缩小为原来的<1倍
            _hratio = h / _h
            if _wratio > _hratio:  # 图片宽度缩小为显示区大小
                _w2 = w
                _h2 = _w2 * _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
            else:  # 图片高度缩小为显示区的大小
                _h2 = h
                _w2 = _h2 / _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
        elif _w < w and _h > h:  # 图片高度大于显示区, 宽度小于显示区
            _wratio = w / _w  # 缩小为原来的<1倍
            _hratio = _h / h
            if _wratio > _hratio:  # 宽的倍数更大
                _w2 = w
                _h2 = _w2 / _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
            else:
                _h2 = w
                _w2 = _h2 / _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
        elif _w > w and _h < h:  # 图片高度大于显示区, 宽度小于显示区
            _wratio = _w / _w  # 缩小为原来的<1倍
            _hratio = h / _h
            if _wratio > _hratio:  # 宽的倍数更大
                _w2 = w
                _h2 = _w2 / _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
            else:
                _h2 = w
                _w2 = _h2 / _hwratio
                a_scaled = pygame.transform.smoothscale(a, (_w2, _h2))
        pos = ((w / 2 - _w2 / 2) + start_x, start_y)
        if screen is None:
            screen = pygame.display.set_mode(imarray.shape[:2][::-1])
        if not screen:
            self.screen.blit(a_scaled, pos)
        else:
            screen.blit(a_scaled, pos)
        pygame.display.update()

        # img=a
        # img_w, img_h = img.get_width(), img.get_height()
        # w, h = screen.get_width(), screen.get_height()
        # x_pos = (w / 2 - img_w / 2)
        # y_pos = (h/ 2 - img_h / 2)
        # '水平方向'
        # if w >= self.width:  # 高度不变,水平拉伸, 显示大小不变
        #     pass
        #     # if h>=height:
        #     #     img_scaled = pygame.transform.smoothscale(img, (img.get_width() * y_ratio, img.get_height() * y_ratio))
        # else:  # 高度不变,水平缩小, 显示大小改变
        #     img_w2 = w * (1 - self.left_right_magin_ratio)
        #     img_h2 = img_w2 * (img_h / img_w)
        #     img = pygame.transform.smoothscale(img, (img_w2, img_h2))
        #     x_pos = w / 2 - img_w2 / 2
        # if h >= self.height:  # 垂直拉伸, 变化位置,不变大小
        #     y_pos = y_pos * (w / self.width) * (1 - self.bottom_magin_ratio)
        # else:  # 垂直缩小, 变化位置,变大小, x,y 均变
        #     img_h2 = img_h * (h / self.height)
        #     img_w2 = img_h2 * (img_w / img_h)
        #     img = pygame.transform.smoothscale(img, (img_w2, img_h2))
        #     x_pos = w / 2 - img_w2 / 2
        #     y_pos = (h / 2 - img_h2 / 2)
        # rect = screen.blit(img, (x_pos, y_pos))
        # pygame.display.update()

    def get_file(self):
        return 'disco.mp4'

    def get_clip(self, filepath):
        video = VideoFileClip(filepath)
        clip = video.subclip(0, video.duration)
        return clip

    def get_rect_pos(self, rect_obj):
        x1, y1 = rect_obj.rect.topleft
        x2 = x1 + rect_obj.rect.width
        y2 = y1 + rect_obj.rect.height
        return [x1, x2, y1, y2]

    def volume(self, volume_value=None):
        '获取音量与设置音量'
        get_volume = {'-65.2': 0, '-57.0': 1, '-51.7': 2, '-47.7': 3, '-44.6': 4, '-42.0': 5, '-39.8': 6, '-37.9': 7,
                      '-36.2': 8, '-34.6': 9, '-33.2': 10, '-32.0': 11, '-30.8': 12, '-29.7': 13, '-28.7': 14,
                      '-27.7': 15, '-26.8': 16, '-25.9': 17, '-25.1': 18, '-24.4': 19, '-23.6': 20, '-23.0': 21,
                      '-22.3': 22, '-21.7': 23, '-21.1': 24, '-20.5': 25, '-19.9': 26, '-19.4': 27, '-18.8': 28,
                      '-18.3': 29, '-17.8': 30, '-17.4': 31, '-16.9': 32, '-16.4': 33, '-16.0': 34, '-15.6': 35,
                      '-15.2': 36, '-14.8': 37, '-14.4': 38, '-14.0': 39, '-13.6': 40, '-13.3': 41, '-12.9': 42,
                      '-12.6': 43, '-12.2': 44, '-11.9': 45, '-11.6': 46, '-11.2': 47, '-10.9': 48, '-10.6': 49,
                      '-10.3': 50, '-10.0': 51, '-9.8': 52, '-9.5': 53, '-9.2': 54, '-8.9': 55, '-8.7': 56, '-8.4': 57,
                      '-8.1': 58, '-7.9': 59, '-7.6': 60, '-7.4': 61, '-7.1': 62, '-6.9': 63, '-6.7': 64, '-6.4': 65,
                      '-6.2': 66, '-6.0': 67, '-5.8': 68, '-5.5': 69, '-5.3': 70, '-5.1': 71, '-4.9': 72, '-4.7': 73,
                      '-4.5': 74, '-4.3': 75, '-4.1': 76, '-3.9': 77, '-3.7': 78, '-3.5': 79, '-3.3': 80, '-3.1': 81,
                      '-3.0': 82, '-2.8': 83, '-2.6': 84, '-2.4': 85, '-2.3': 86, '-2.1': 87, '-1.9': 88, '-1.8': 89,
                      '-1.6': 90, '-1.4': 91, '-1.2': 92, '-1.1': 93, '-0.9': 94, '-0.8': 95, '-0.6': 96, '-0.5': 97,
                      '-0.3': 98, '-0.1': 99, '0.0': 100}
        set_volume = {0: -65.2, 1: -57.0, 2: -51.7, 3: -47.7, 4: -44.6, 5: -42.0, 6: -39.8, 7: -37.9, 8: -36.2,
                      9: -34.6, 10: -33.2, 11: -32.0, 12: -30.8, 13: -29.7, 14: -28.7, 15: -27.7, 16: -26.8, 17: -25.9,
                      18: -25.1, 19: -24.4, 20: -23.6, 21: -23.0, 22: -22.3, 23: -21.7, 24: -21.1, 25: -20.5, 26: -19.9,
                      27: -19.4, 28: -18.8, 29: -18.3, 30: -17.8, 31: -17.4, 32: -16.9, 33: -16.4, 34: -16.0, 35: -15.6,
                      36: -15.2, 37: -14.8, 38: -14.4, 39: -14.0, 40: -13.6, 41: -13.3, 42: -12.9, 43: -12.6, 44: -12.2,
                      45: -11.9, 46: -11.6, 47: -11.2, 48: -10.9, 49: -10.6, 50: -10.3, 51: -10.0, 52: -9.8, 53: -9.5,
                      54: -9.2, 55: -8.9, 56: -8.7, 57: -8.4, 58: -8.1, 59: -7.9, 60: -7.6, 61: -7.4, 62: -7.1,
                      63: -6.9, 64: -6.7, 65: -6.4, 66: -6.2, 67: -6.0, 68: -5.8, 69: -5.5, 70: -5.3, 71: -5.1,
                      72: -4.9, 73: -4.7, 74: -4.5, 75: -4.3, 76: -4.1, 77: -3.9, 78: -3.7, 79: -3.5, 80: -3.3,
                      81: -3.1, 82: -3.0, 83: -2.8, 84: -2.6, 85: -2.4, 86: -2.3, 87: -2.1, 88: -1.9, 89: -1.8,
                      90: -1.6, 91: -1.4, 92: -1.2, 93: -1.1, 94: -0.9, 95: -0.8, 96: -0.6, 97: -0.5, 98: -0.3,
                      99: -0.1, 100: 0.0}
        pointer = ctypes.POINTER(IAudioEndpointVolume)
        devices = AudioUtilities.GetSpeakers()
        dc = devices.Activate(IAudioEndpointVolume._iid_, comtypes.CLSCTX_ALL, None)
        volume = ctypes.cast(dc, pointer)
        if volume_value is not None:
            volume.SetMasterVolumeLevel(set_volume[volume_value], None)
        else:
            v = '%.1f' % volume.GetMasterVolumeLevel()
            return get_volume[v]

    def get_dis_size(self):
        dis = pygame.display.Info()
        w, h = dis.current_w, dis.current_h
        return w,h

class window:
    def __init__(self):
        self.root=root=Tk()
        self.root.title('音视频播放器') # 音视频播放器
        self.root.resizable(False, False)  # 固定窗口大小
        label =Label(root, text='音视频播放器',font=('黑体',25),fg='magenta')
        label.place(x=90, y=10)
        menu=Menu(self.root)  #创建主目录
        helpmenu=Menu(menu, tearoff=False)  #创建子目录
        menu.add_cascade(label='帮助', menu=helpmenu)  #设置菜单名称label='帮助',在主目录中添加子目录
        #添加子目录菜单内加名称,以及指令
        helpmenu.add_radiobutton(label='使用说明', command=self.introduct, font=('黑体', 10))# variable=editVar, value=1
        self.root.config(menu=menu)  # 在root中放置主目录

        self.status=StringVar()
        label = Label(root, text='选择文件', font=('黑体', 12))
        label.place(x=39, y=99)
        self.entry1=Entry(root)
        self.entry1.place(x=120,y=100)

        self.buttonbrowser1=Button(root,text='浏览',font=('黑体',12),     #按钮,功能键
                                          command=self.browser)
        self.buttonbrowser1.place(x=282,y=95)

        self.buttonconv=Button(root,text='启动播放',fg='blue',font=('黑体',16),
                                       command=self.conv)
        self.buttonconv.place(x=130,y=157)

    def introduct(self):
        messagebox.showinfo('帮助', '''
        F1: 重新播放
        播放与暂停: 启动播放后点击界面即可进行播放与暂停
        Left: 快退
        Right: 快进
        Up: 音量+
        Down: 音量—
        ''')

    def mainloop(self):                                             #主屏幕运行框,设置最大最小尺寸
        self.root.minsize(380,250)
        self.root.maxsize(380,250)
        self.root.mainloop()

    def browser(self):
        '''选择文件浏览框'''
        directory=filedialog.askopenfilenames(title='音视频播放器')
        if directory:
            self.entry1.delete(0,END)
            self.entry1.insert(END,set(directory))
    def savepath(self):
        '''保存路径浏览框'''
        savepath = filedialog.askdirectory(title='Zip大师')
        if savepath:
            self.entry2.delete(0,END)
            self.entry2.insert(END,savepath)
    def read_filenames(self):
        with open('filenames.txt','r') as f:
            for i in f.readlines():
                yield i.replace('\n', '')
    def renameall(self,examplename): #命名:无,(25),nihao(2),nihao.pdf  nihao(25).pdf  6中命名方式,可先分有无格式,再分有无括号,再分有无后缀
        i=0
        for c in self.read_filenames():
            #C:/Users/xiaosalang/Desktop/能耗SDN雾计算/1.docx
            filenametype =c.split('/')[-1]  #1.docx
            filep = c.replace(filenametype, '')  #C:/Users/xiaosalang/Desktop/能耗SDN雾计算/
            filetype = filenametype.split('.')[-1]  #docx
            if examplename == '':
                newname0 = filep + str(i + 1) + "." + filetype  # 加序号从1开始
                newname = newname0.strip()
                os.renames(c, newname)
            else:
                pat = re.compile("(?<=\()\S+(?=\))")  # (?<=exp)是以exp开头的字符串, 但不包含本身.\S 匹配任何非空白字符
                sn = int(re.findall(pat, examplename)[0].replace('(', '').replace(')', ''))  # sn=startnum
                if sn == '':  # 未匹配到数字
                    newname0 = filep + examplename + str(i + 1) + "." + filetype  # 在输入边加序号从1开始
                    newname = newname0.strip().replace('(', '').replace(')', '')
                    os.renames(c, newname)
                else:  # 如果匹配到数字sn,则递增
                    newname0 = filep + examplename.replace('%d' % sn, '%d' % (sn + i)) + "." + filetype
                    newname = newname0.strip().replace('(', '').replace(')', '')
                    os.rename(c, newname)
            i+=1

    def conv(self):
        def _conv():
            filepaths = list(eval(self.entry1.get()))
            if filepaths == '':
                messagebox.showerror('Python tkinter', '请选择文件')
                return
            try:
                t= threading.Thread(target=Player, args=(filepaths[0],))
                t.setDaemon(True)
                t.start()
            except Exception as e:
                print(e)
        threading.Thread(target= _conv).start()
window=window()
window.mainloop()







  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潇洒郎

您打赏我发自肺腑努力创作的心灵

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值