简体   繁体   中英

How to define fast forward button in pygame using python?

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.

Please help me to solve this problem

Here is my code:

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() also give me errors like

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

I solved your task.

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, ie 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!

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.

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(...) .

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()

Prints to console:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM