简体   繁体   中英

How to play a sound in a "Hello World" Python program (kids class context)

I'm trying to play a sound in a "Hello World" Python program for a children's class. I used the pygame library for that, but the program can't open the sound file. How can I fix this?

 import pygame
 pygame.init()
 song = pygame.mixer.Sound('robot.wav')
 song.play()
 print ("Hello, world!")

 Error = song = pygame.mixer.Sound('robot.wav')
 pygame.error: Unable to open file 'robot.wav'

First of all, after pygame.init() you need pygame.mixer.init(). Second of all, you can't just load files from anywhere. For your program to load robot.wav, you either need to put robot.wav in the same directory as your program file, or you need to specify the entire path to robot.wav. C:/MyPrograms/HelloWorld/robot.wav is an example of a file path, if you are using Windows.

It is also possible that the sound file is corrupted or in the wrong format (eg not a wav file, even though it is named .wav).

Refer to:

http://www.pygame.org/docs/ref/mixer.html

http://www.pygame.org/docs/

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