0

So i am creating a class that have to be called by other class and when i try it with the ide of pycharm it is working but with the console i am having some problems. (if it works with the ide it should not be problem of the path)

The class MySoundPygame:

import pygame as pygame
import time


class MySoundPygame:
    def __init__(self, son):
        #print("constructor")
        self.son = son
        pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=512)
        pygame.mixer.init()
        self.sound1 = pygame.mixer.Sound(son)

    def setSong(self, s):
        try:
            print(s)
            self.sound1 = pygame.mixer.Sound(s)
            self.sound1.play()
            time.sleep(self.sound1.get_length())
            res = {
                'code': 200,
                'message': 'ok'
            }
            return res

        except:
            res = {
                'code': 500,
                'message': 'Error'
            }
            return res 

The general class that includes play music and other things, i am calling it with:


from .sound.MySoundPygame import MySoundPygame
song = MySoundPygame('/home/pi/Desktop/python/proyecto/audio/intro.mp3')

    def putSoundTrack(self, nameSong):
        print("entra")
        res = song.setSong(nameSong)
        print(res)
        return res

But i get this error in console:

 File "/home/pi/Desktop/python/proyecto/sound/MySoundPygame.py", line 13, in __init__
    self.sound1 = pygame.mixer.Sound(son)
pygame.error: Unable to open file '/home/pi/Desktop/python/proyecto/audio/intro.mp3'

Thanks for the help!

Daniel IG
  • 31
  • 6
  • *"if it works with the ide it should not be problem of the path"* - No. it is definitely a problem with the path. The path needs to be relative to the current working directory instead of relative to the .py file. In the IDE the current working directory is the same as the directory of the .py files. This is not the case when you run it from the console. – Rabbid76 Jun 09 '21 at 14:22

1 Answers1

0

[...] if it works with the ide it should not be problem of the path [...]

No, it is a problem with the path.

The path must be relative to the current working directory and not relative to the source (.py) file. In the IDE the current working directory is the same as the directory of the source files. This is not the case when you run it from the console.

One solution is to change the working directory at the begin of the application. See Could not open resource file: pygame.error: Couldn't open sprite/test_bg.jpg:

import os

sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174