How to make animated face speak using pygame and pyttsx - python

I want to make animated talking character using pygame and python text to speech pyttsx module.
Below is my code I am figuring out how can I achieve this.
import pygame,time
import sys,math
import pyttsx
from pygame import gfxdraw
PI = math.pi;
pygame.init()
screen = pygame.display.set_mode((640, 480))
back = (255,255,255);
color = (255,255,0);
mouth_flag = 'false';
engine = pyttsx.init()
engine.say('Good morning.')
while True:
time.sleep( 0.25 )
screen.fill(back);
pygame.gfxdraw.filled_circle(screen,320,240,100,color);
pygame.gfxdraw.filled_circle(screen,270,210,20,(0,0,0));
pygame.gfxdraw.filled_circle(screen,370,210,20,(0,0,0));
if mouth_flag=='false':
pygame.gfxdraw.arc(screen,320,240,75,25, 155, (0,0,0))
mouth_flag='true';
else:
pygame.gfxdraw.line(screen,270,290,370,290,(0,0,0));
mouth_flag='false';
pygame.display.update();
engine.runAndWait();

Finally I resolved by multi threading concept in python. I referred the example
mentioned here https://www.geeksforgeeks.org/multithreading-python-set-1/
I created 2 threads one to run animation and other to run engine.runAndWait();

Related

Python pygame displaying images and audio files from other users

When my script converted to .exe is launched by a person who does not have the necessary images and audio files, these images and audio files are not displayed in his program.
How can I make everyone see them?
Is it possible to download files from the Internet or something else?
import pyautogui as pg
from pygame import mixer
import pygame
import pyglet
from tkinter import *
from tkinter import messagebox
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import requests as rqs
pygame.mixer.init()
pygame.init()
pygame.mixer.music.set_volume(100)
mixer.music.load('D:\Programs\games\Python\Projects\MEDIA\Sm.mp3')
pp = pygame.image.load('D:\Programs\games\Python\Projects\MEDIA\pp.png')
pg.alert("Вы установили смачный вирус!", "ERROR", button = "Продолжить" )
pg.confirm("Точно продолжить?", ("НЕТ!"))
pg.password("Введите пароль для отмены")
pg.alert("Пароль неверный!", "ERROR" )
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate( IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
volume.SetMasterVolumeLevel(-0.0, None)
screen = pygame.display.set_mode((1920, 1080))
screen.blit(pp, (0, 0))
volume.SetMasterVolumeLevel(-0.0, None)
time.sleep(5)
volume.SetMasterVolumeLevel(-0.0, None)
mixer.music.play(-1)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
screen = pygame.display.set_mode((1920, 1080))
screen.blit(pp, (0, 0))
mixer.music.play(-1)
pg.move(10000, 10000)
pg.move(10000, 10000)
volume.SetMasterVolumeLevel(-0.0, None)
pygame.display.update() ```
It isn't possible to display files that aren't there. The easiest solution would be to simply include the necessary files when sending your programme to users (you might also want to try using relative file paths instead of assuming other users will have everything saved in 'D:\Programs\games\Python\Projects'.
If you want to go for the download route, try hosting the necessary files publicly on Google Drive or something similar and taking a looking at this question if you are unsure how to download the files.

Pygame Import Error: cannot import name _camera while accessing webcamera

I reinstall pygame 3 times but issue not get resolved. Below is my code.
import pygame
import pygame.camera
import time
pygame.init()
pygame.camera.init()
camlist = pygame.camera.list_cameras()
cam = pygame.camera.Camera("C:/Program Files/iBall Face2Face ROBO K20 Webcam/VideoCap",(640,480))
cam.start()
time.sleep(0.1) # You might need something higher in the beginning
img = cam.get_image()
pygame.image.save(img,"C:/Users/mswatg05/Desktop/filename.jpg")
cam.stop()
By default, the camera extension is only enabled on linux builds. Try using a third party compile, and install VideoCapture from the same place.

Pygame grabbing console input when using framebuffer

I have a Raspberry Pi with a PiTFT module. I'm wanting to use Pygame to display information on the module using the framebuffer (without X). I have all the display stuff working but the problem is that pygame is grabbing the input from the keyboard so that I can't even change the terminal with alt 1-7.
This task is supposed to run in the background so this is not desired behavior. I can't find any way to disable it though. It looked like pygame.event.set_grab() might have been appropriate but did not help. Here is a cut-down version of my code which exhibits the same issue.
import os
import pygame
import time
from time import gmtime,strftime,localtime
class pytest :
screen = None
def __init__(self):
os.environ["SDL_FBDEV"] = "/dev/fb1"
try:
pygame.display.init()
except pygame.error:
print 'Init failed.'
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
pygame.event.set_grab(0)
pygame.font.init()
self.font = pygame.font.SysFont("", 30)
def __del__(self):
"Destructor to make sure pygame shuts down, etc."
def test(self):
lightblue = (92, 92, 176)
self.screen.fill(lightblue)
tm=time.strftime("%H:%M:%S",localtime())
t=self.font.render(tm,1,(255,255,155))
self.screen.blit(t,(240,00))
pygame.display.update()
scope = pytest()
while 1:
scope.test()
pygame.event.pump()
time.sleep(1)

Display IO Stream from Raspberry Pi Camera as video in PyGame

I'm working on a project that requires me to have a viewfinder (barcode scanner).
I'm doing this with the Raspberry Pi Camera Module by the picamera python module, and I've got the whole detection and whatnot programmed.
Now I need to figure out how to display the preview from the Pi's Camera Module in a PyGame movie module.
(If there's a better way to display video from an IO Stream in PyGame, please let me know.)
The reason I need to display it in PyGame is because I'll need to overlay controls on top of the video and be able to get input from a touchscreen I'm going to use as the viewfinder/screen for the Pi/project.
As far as I can see from the pygame.movie documentation, pygame.movie only loads from a file. Is there a way that I could convert the stream into a file-like object and have PyGame play from that?
Basically put, I need a way to take the io.BytesIO stream created in this example code, and display it in PyGame.
If I understand excatly , you need to instant and infinite preview from camera module to your screen.
there is a way that I figure it out. first you must install Official V4L2 driver.
sudo modprobe bcm2835-v4l2
reference https://www.raspberrypi.org/forums/viewtopic.php?f=43&t=62364
and than you should create a python file to compile and code this
import sys
import pygame
import pygame.camera
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640,480),0)
cam_list = pygame.camera.list_cameras()
cam = pygame.camera.Camera(cam_list[0],(32,24))
cam.start()
while True:
image1 = cam.get_image()
image1 = pygame.transform.scale(image1,(640,480))
screen.blit(image1,(0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
cam.stop()
pygame.quit()
sys.exit()
this code from http://blog.danielkerris.com/?p=225 , in this blog they did with a webcam. you define your camera module as a webcam with v4l2 driver
also you should check this tutorial https://www.pygame.org/docs/tut/camera/CameraIntro.html
I hope this will works for you
You can do this with the 'pygame.image.frombuffer' command.
Here's an example:
import picamera
import pygame
import io
# Init pygame
pygame.init()
screen = pygame.display.set_mode((0,0))
# Init camera
camera = picamera.PiCamera()
camera.resolution = (1280, 720)
camera.crop = (0.0, 0.0, 1.0, 1.0)
x = (screen.get_width() - camera.resolution[0]) / 2
y = (screen.get_height() - camera.resolution[1]) / 2
# Init buffer
rgb = bytearray(camera.resolution[0] * camera.resolution[1] * 3)
# Main loop
exitFlag = True
while(exitFlag):
for event in pygame.event.get():
if(event.type is pygame.MOUSEBUTTONDOWN or
event.type is pygame.QUIT):
exitFlag = False
stream = io.BytesIO()
camera.capture(stream, use_video_port=True, format='rgb')
stream.seek(0)
stream.readinto(rgb)
stream.close()
img = pygame.image.frombuffer(rgb[0:
(camera.resolution[0] * camera.resolution[1] * 3)],
camera.resolution, 'RGB')
screen.fill(0)
if img:
screen.blit(img, (x,y))
pygame.display.update()
camera.close()
pygame.display.quit()

pygame.error: file not a windows.bmp file (have looked at other similar questions but unsuccessful so far)

I'm very new to pygame, and am using the book "Beginning Game developement with Python and Pygame". I have pretty much typed the example code and keep getting the same
"pygame error: file not a windows.bmp file"
and would like to be able to load jpg/png as in the example in the book. I'm pretty sure I'm in the right directory for mine to work and the images I wanted to use are the same format as in the example. I have also searched for solutions but none of the answers seemed to work for me.
The code from the book is as follows (I have python 2.7.4, Ubuntu 13.04 and (I think) pygame 1.2.15):
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
my version of the code so far:
import os.path
background = os.path.join('Documents/Python/Pygame','Background.jpg')
cursor_image = os.path.join('Documents/Python/Pygame','mouse.png')
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
Thanks for your help :)
I can almost guarantee that you're getting your paths wrong. In your code, you've put in relative paths, meaning that pygame is looking for your assets in subfolders of the working directory (the directory where you execute your code).
A demo of how I think you would have to have things laid out and where your code is looking is below - in this example you would have a command prompt open in /home/your_username/Documents/my_games (or ~/Documents/my_games) and you'd be running python your_game_script.py.
|---home
|---your_username
|---Documents
|---some_subfolder
|---my_games
|---your_game_script.py
|---Documents
|---Python
|---Pygame
|---Background.jpg
|---mouse.png
This would work, but I suspect you don't have your folders set up this way, and that's the reason it's not working. If you run an interactive python prompt in the same folder as your game script, try the following:
import os
os.path.isfile('Documents/Python/Pygame/Background.jpg')
os.path.isfile('Documents/Python/Pygame/mouse.png')
I suspect the result will be false for both - meaning the files couldn't be found at that subfolder location. I would recommend that you have the following structure for your game files:
|---my_game
|---your_game_script.py
|---images
|---Background.jpg
|---mouse.png
Then in your_game_script.py you can load the files in the following way:
background = 'images/Background.jpg' #relative path from current working dir
cursor_image = 'images/mouse.png' #relative path from current working dir
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()

Categories