2016-08-21 8 views
0

実行時にランダムなwavファイルを再生するプログラムがあります。私はプログラムを実行するときしかし、私はこのエラーを取得する:PygameはRaspberry Piの曲を開くことができません

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 
' 

は、これはコードです:

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 

とlist.txtには、次のようになります。

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

プログラムが実行されますRaspbianのRaspberry Piで、Pygameを使って このエラーはなぜ発生しますか?

+0

'songs.append(x)'のような縫い目は決して届かず、それは問題の可能性があります – juanjo

答えて

1
breakを入れて試してみてください

あなたのコードでは、改行文字を含むファイルの行全体を読み込んでいます。リストの最大インデックスよりも1小さいので、あなたはまた、いくつかの点で範囲外のインデックスに到達することが

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

に置き換えることができます

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

を持つのではなく、することでこれを回避することができます長さ、あなたが必要との意味:私のコードで

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

を私はrandintの代わりにrandom.randintを入れていた(それはあなたのためにこのようなものだ場合、私は知らない)

+0

これは完璧に働いています、ありがとう:) – Vigge93

0
  1. あなた.wavsが
  2. は、彼らが呼ばれていることを確認し、あなたの.pyと同じフォルダにあることを確認してください 'song1.wavという'
  3. if not x == '':
  4. songs.append
関連する問題