如何使用python在pygame中定义快进按钮? [英] How to define fast forward button in pygame using python?

查看:117
本文介绍了如何使用python在pygame中定义快进按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个音乐播放器,我想在其中制作 fastforward 按钮(如果点击 fastforward 按钮,则当前播放的歌曲将增加 10 秒)但我可以'正确定义它.我也尝试了 pygame 的 set_pos() 方法,但它不适用于我的脚本.

I had made a music player where I want to make fastforward button (if the fastforward button click then the current playing song will increase by 10seconds) but I can't define it properly. I also try set_pos() method of pygame but it is not working for my script.

请帮我解决这个问题

这是我的代码:

fast_forward_icon= tk.PhotoImage(file=__file__+ '/../images/JPEG, PNG/icons/fast_forward.png')
def fast_forward(event=None):
   def func():
      global progressbar_music
      current_song_Length = mixer.music.get_pos()//1000
      print(current_song_Length)
      # mixer.music.pause()
      f= current_song_Length+10
      mixer.music.set_pos(f)
      progressbar_music['value']=f
      # mixer.music.progressbar_music(seconds=current_song_Length+10)
      progressbar_music_starttime.configure(text='{}'.format(str(datetime.timedelta(seconds=f))))
      progressbar_music.after(2,func)
   func()

fastForwardBtn = Button(root, bg='#310A3D', image=fast_forward_icon, command=fast_forward)
fastForwardBtn.place(x=600, y=500, relwidth=.04, relheight=.08)

set_pos() 也会给我类似的错误

Exception in Tkinter callback Traceback (most recent call last):
File "C:\Users\soham\AppData\Local\Programs\Python\Python36\lib\tkinter_init_.py", 
line 1702, in call return self.func(*args) File "C:\Users\soham\AppData\Local\Programs\Python\Python36\lib\tkinter_init_.py", 
line 746, in callit func(*args) File "e:/python projects/MUSIC PLAYER/music_player.py", 
line 346, in func mixer.music.set_pos(f) pygame.error: 
set_pos unsupported for this codec

推荐答案

我解决了你的任务.

主要问题不是由于 MP3 编解码器问题,而是因为您的音乐应该被加载/播放/暂停以便 set_pos() 工作,即在快进之前您需要下一个额外的行:

Main problem was not due to MP3 codec problem, but because your music should be loaded/played/paused in order for set_pos() to work, i.e. you need next extra lines before doing fast forward:

mixer.music.load('test.mp3')
mixer.music.play()
mixer.music.pause()

只有这样你才能使用快进,它才有效!

Only then you can use fast forward and it works!

您还需要稍后执行 mixer.music.unpause() 以便从您的快进位置(由 set_pos() 设置)开始播放音乐.也可以在没有 pause()/unpause() 的情况下进行快进,只播放音乐,所以 play() 应该被调用,如果现在没有播放.

Also you need to do mixer.music.unpause() later in order to start music playing from your fast-forwarded position (set by set_pos()). Also fast forwarding may also work without pause()/unpause(), just music should be playing, so play() should be called if it is not playing now.

下面是完整的工作代码,为了使示例完全可运行,它有一些其他修改,但其余的修改不是解决您的任务所必需的.主要修改之一是我实现了用于加载 MP3/PNG 资源的函数 get_url_file(...),因此该示例完全独立,无需额外文件即可运行,因为 StackOverflow 没有允许附加文件,因此我从远程 HTTP 存储加载它们.在我使用 get_url_file(...) 的地方只使用像 path/to/test.mp3 这样的文件路径.

Full working code below, it has some other modifications in order to make example fully runnable, but remaining modifications are not necessary to solve your task. One of main modification is that I implemented function get_url_file(...) that I used to load MP3/PNG resources so that example is fully self-contained an runnable without extra files, because StackOverflow doesn't allow attaching file, hence I load them from remote HTTP storage. Use just file path like path/to/test.mp3 in places where I used get_url_file(...).

在运行下一个代码之前,通过 python -m pip install --upgrade pgzero pygame<2.0 requests 一次安装 python pip 模块.

Also before running next code install python pip modules one time by python -m pip install --upgrade pgzero pygame<2.0 requests.

# Needs: python -m pip install --upgrade pgzero pygame<2.0 requests
import tkinter as tk, datetime, pgzrun
from pygame import mixer

root = tk.Tk()

def fast_forward(event = None):
    def func():
        global progressbar_music
        mixer.music.play()
        mixer.music.pause()
        current_song_Length = mixer.music.get_pos() // 1000
        print(current_song_Length)
        # mixer.music.pause()
        f = current_song_Length + 10
        mixer.music.set_pos(f)
        print('{}'.format(str(datetime.timedelta(seconds = f))))
        mixer.music.unpause()
        #progressbar_music['value'] = f
        # mixer.music.progressbar_music(seconds=current_song_Length+10)
        #progressbar_music_starttime.configure(text = '{}'.format(str(datetime.timedelta(seconds = f))))
        #progressbar_music.after(2, func)

    func()
    
def get_url_file(url, *, fsuf = '', as_ = 'bytes', b64 = False, state = {}):
    import requests, io, atexit, base64, tempfile, shutil, secrets, os
    res = requests.get(url)
    res.raise_for_status()
    data = res.content
    if b64:
        data = base64.b64decode(data)
    if as_ == 'bytes':
        return data
    elif as_ == 'file':
        return io.BytesIO(data)
    elif as_ == 'path':
        if 'td' not in state:
            state['td'] = tempfile.TemporaryDirectory()
            state['etd'] = state['td'].__enter__()
            state['std'] = str(state['etd'])
            def cleanup():
                state['td'].__exit__(None, None, None)
                if os.path.exists(state['std']):
                    shutil.rmtree(state['std'])
            atexit.register(cleanup)
        path = state['std'] + '/' + secrets.token_hex(8).upper() + fsuf
        with open(path, 'wb') as f:
            f.write(data)
        return path
    else:
        assert False, as_

mixer.music.load(get_url_file('https://pastebin.com/raw/8LAeZc1X', as_ = 'file', b64 = True))
fast_forward_icon = tk.PhotoImage(file = get_url_file('https://i.stack.imgur.com/b2wdR.png', as_ = 'path'))

fastForwardBtn = tk.Button(root, bg = '#310A3D', image = fast_forward_icon, command = fast_forward)
fastForwardBtn.place(x = 10, y = 10, relwidth = .7, relheight = .7)

tk.mainloop()
pgzrun.go()

打印到控制台:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
0
0:00:10

这篇关于如何使用python在pygame中定义快进按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆