简体   繁体   中英

Python pygame “an integer is required”

I have a function using gTTS, pygame and os modules:

from gtts import gTTS
import pygame as pg
from os import remove as OSremove

music = pg.mixer.music

def speak(x):
     sound = gTTS(text=x, lang="pl")
     sound.save("temp.mp3")
     pg.mixer.init()
     music.load("temp.mp3")
     music.play("temp.mp3")
     pg.quit()
     OSremove("temp.mp3")

And I'm getting an error: TypeError: an integer is required (got type str). Image here because I have 5 rep

Okay, the answer above is correct as far as it goes, but let's look a little deeper at it since you're clearly new to this.

First of all, when you get an error message, read it . In this case, it's telling you that it wants an integer and you're giving it a string. So, clearly, you misunderstood something.

Next, have a look at the documentation. Google pygame.mixer.music.play and it'll pop right up.

https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.play

Next, look at the documentation. In this case it says: 这个

play takes two arguments, loops and start , both of them defaulting to 0. No strings -- so you're giving it the wrong argument.

Look further on the Google results and you'll see an SO question: How play mp3 with pygame

And that will lead you to some example code in another SO answer.

You don't need to pass the name of the music file to the play function. Just call play() without parameters and it should work.

See the documentation of the play function:

http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.play

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM