Vigge93 Vigge93 - 3 months ago 10
Python Question

Pygame can't open song on raspberyy pi

I have program that plays a random wav file when run. However when i run the program i get this error:

Traceback (most recent call last):
File "pi/home/python_music/music.py", line 19, in <module>
pygame.mixer.music.load(song)
error: Couldn't open 'Song1.wav
'


This is the code:

import pygame
import random

f = open('List.txt', 'r+')
songs = []

while True:
x = f.readline()
if x == '':
break
songs.append(x)
f.close()

while True:
y = randint(0, len(songs))
song = songs[y]

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

while True:
if pygame.mixer.music.get_busy()== False:
pygame.mixer.quit()
break


and List.txt looks like this:

Song1.wav
Song2.wav
Song3.wav
.
.
.
Song12.wav


The program is run on a rasberry pi with raspbian and using pygame.
Why do i get an error?

Answer

In your code, you're reading the entire line of the file including the newline character. You can avoid this by instead of having

f = open('List.txt', 'r+')
songs = []
while True:
    x = f.readline()
    if x == '':
        break
        songs.append(x)
    f.close()
 y = randint(0, len(songs))

It can be replaced with

f = open('List.txt', 'r+')
songs = f.read().splitlines()
f.close()

You will also reach an index out of range at some point because the max index of a list is one less than the length, meaning you need:

y = random.randint(0, len(songs) - 1)

In my code I had to put random.randint instead of randint (I don't know if it's like this for you)