Merlin1230
Merlin1230

Reputation: 23

How do I use the same mp3 file more then once?

import tkinter as tk 
from tkinter import filedialog
from pygame import mixer

mixer.init()

firsttime = False
song2switch = True

root = tk.Tk()
 
canvas = tk.Canvas(root, width=400, height=250)
canvas.pack()

def loadsong1():
    global song1
    song1 = tk.filedialog.askopenfile(parent=root, initialdir="C:/",title="choose first song",filetypes=[("mp3 files", ".mp3")])
def loadsong2():
    global song2
    song2 = tk.filedialog.askopenfile(parent=root, initialdir="C:/",title="choose second song",filetypes=[("mp3 files", ".mp3")])
def play():
    mixer.music.load(song1)
    mixer.music.play()
def switch():
    global firsttime
    global song2switch
    global time_of_song
    if firsttime == False:
        time_of_song = mixer.music.get_pos()
        time_of_song /= 1000
        mixer.music.stop()
        mixer.music.load(song2)
        mixer.music.play(start = time_of_song)
        firsttime = True
        song2switch = False
    else:
        if song2switch == False:
            time_of_song = mixer.music.get_pos()
            time_of_song /= 1000
            mixer.music.stop()
            mixer.music.load(song1)
            mixer.music.play(start = time_of_song)
            song2switch = True

playbutton = tk.Button(canvas,text="PLAY",command=play)
canvas.create_window(200,240,window=playbutton)
load1button = tk.Button(canvas, text="Load Song One",command=loadsong1)
canvas.create_window(100,240,window=load1button)
load2button = tk.Button(canvas, text="Load Song Two", command=loadsong2)
canvas.create_window(300,240,window=load2button)
switchbutton = tk.Button(canvas, text="SWITCH", command=switch)
canvas.create_window(200,200, window=switchbutton)

root.mainloop()


I'm trying to make this music player that can switch between two songs while keeping the same time between each other (for example, when I switch a song that has been playing for a minute, the other will start a minute in), but when i try to switch it to the first song, it makes this error:

pygame.error: Couldn't read first 12 bytes of audio data

How do I fix this?

Upvotes: 2

Views: 73

Answers (1)

acw1668
acw1668

Reputation: 46688

It is because you have used askopenfile(...) which will open the selected file in read mode and return the file handle.

When you switch to song2, song1 is closed. When you want to switch back to song1 again, mixer.music.load(song1) will fail with exception because the file is already closed.

Use askopenfilename() instead of askopenfile().

Note 1: mixer.music.get_pos() returns the elapsed time relative to start, not the beginning.

Note 2: your switching logic will not work properly after switching two times.

Upvotes: 1

Related Questions