1

I get

File "C:/Users/Acer/PycharmProjects/pythonProject9/main.py", line 26, in play
    pygame.mixer.music.load(song)
pygame.error: Couldn't open 'D:/gui/audio/<_io.TextIOWrapper name='D:/gui/audio/Metallica - The_Unforgiven.mp3' mode='r' encoding='cp1252'>.m

I don't know what to do

Here's the code:

def add_song():
    song = filedialog.askopenfile(initialdir='D:/gui/audio', title='Choose a song', filetypes=(('mp3 Files.', '*.mp3'), ))

    # Add songs to list box
    song_box.insert(END, song)
# Play selected song
def play():
    song = song_box.get(ACTIVE)
    song = f'D:/gui/audio/{song}.mp3'

    pygame.mixer.music.load(song)
    pygame.mixer.music.play(loops=0)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 3
    This line `song = f'D:/gui/audio/{song}.mp3'` assumes that `song` is a string. It is not a string, it's a file. – BoarGules Nov 15 '20 at 08:15

1 Answers1

0

The argument to pygame.mixer.music.load() must be the filename of the song and not a file object. Get the name from the file object (see Get path from open file in Python) to load the music:

pygame.mixer.music.load(song)

pygame.mixer.music.load(song.name)

Minimal example:

import pygame
import tkinter.filedialog

song = tkinter.filedialog.askopenfile(filetypes = (('mp3 Files.', '*.mp3'), ))

pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(song.name)
pygame.mixer.music.play()

while pygame.mixer.music.get_busy():
    pygame.event.poll()

pygame.quit()
exit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174