반응형

사운드를 로드하고 플레이 해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import pygame
 
pygame.init()
pygame.display.set_caption("Super fun game development")
screen = pygame.display.set_mode((640480))
clock = pygame.time.Clock()
running = True
 
player = pygame.image.load("player.png").convert()
player.set_colorkey(player.get_at((00)))
player_size = (player.get_width()*1.5, player.get_height()*1.5)
player = pygame.transform.scale(player, player_size)
player_pos = player.get_rect()
player_pos.center = (screen.get_width()/2, screen.get_height()/2)
 
sound = pygame.mixer.Sound("music.mp3")
# 사운드 리소스를 로드하고 오브젝트를 반환한다.
sound.play()
# 로드한 사운드 오브젝트를 플레이한다.
 
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
 
 
    screen.fill("black")
    screen.blit(player, player_pos)
    
    pygame.display.flip()
    clock.tick(60)
 
pygame.quit()
 

 

music.mp3
4.01MB

 

로드한 사운드가 플레이 된다.

 

반응형
Posted by J-sean
:
반응형

이미지를 로드하고 출력해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import pygame
 
pygame.init()
pygame.display.set_caption("Super fun game development")
screen = pygame.display.set_mode((640480))
clock = pygame.time.Clock()
running = True
 
player = pygame.image.load("player.png").convert()
# 플레이어 이미지를 로드하고 디스플레이와 일치하는 color format과 depth로 변환한다.
player.set_colorkey(player.get_at((00)))
# 이미지의 (0, 0) 픽셀을 colorkey로 사용한다. (0, 0) 픽셀과 같은 색상은 투명하게
# 표시된다.
player_size = (player.get_width()*1.5, player.get_height()*1.5)
player = pygame.transform.scale(player, player_size)
# 이미지를 1.5배 확대한다.
player_pos = player.get_rect()
player_pos.center = (screen.get_width()/2, screen.get_height()/2)
# 이미지의 위치를 화면 중앙으로 설정한다.
 
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
 
 
    screen.fill("black")
    screen.blit(player, player_pos)
    # 스크린에 이미지를 출력한다.
    
    pygame.display.flip()
    clock.tick(60)
 
pygame.quit()
 

 

 

player.png

 

colorkey가 적용되어 이미지가 깔끔하게 출력된다.

 

반응형
Posted by J-sean
:
반응형

Pygame으로 게임을 개발하기 위한 기본 코드를 작성해 보자. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Example file showing a basic pygame "game loop"
# pygame 기본 셋업
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'= '1'
# pygame 실행시 표시되는 메세지를 보이지 않게 한다.
# pygame을 import 하기 전에 설정해야 한다.
import pygame
 
# pygame setup
pygame.init()
pygame.display.set_caption("Super fun game development")
# 게임창 제목 표시
screen = pygame.display.set_mode((640480))
# 게임창 크기를 640X480으로 설정.
clock = pygame.time.Clock()
running = True
 
while running:
    # poll for events
    # pygame.QUIT event means the user clicked X to close your window
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
 
    # fill the screen with a color to wipe away anything from last frame
    screen.fill("black")
 
    # RENDER YOUR GAME HERE
    pygame.draw.circle(screen, "gray", screen.get_rect().center, 100)
    # 스크린 중앙에 회색원을 하나 그린다.
 
    # flip() the display to put your work on screen
    pygame.display.flip()
 
    clock.tick(60)  # limits FPS to 60
 
pygame.quit()
 

 

 

코드를 실행하면 검은 배경에 회색 원이 하나 표시된다.

 

PYGAME_HIDE_SUPPORT_PROMPT를 설정하지 않으면 위와 같은 메세지가 표시된다.

 

반응형
Posted by J-sean
:
반응형

파이썬에서 Google Speech to Text를 사용해 보자.

 

SpeechRecognition을 설치한다.

 

마이크 사용을 위해 PyAudio를 설치한다.

 

소스를 입력하고 실행한다.

 

완벽하지는 않지만 꽤 잘 인식한다. ('현'이 아니라 '션'이었다)

 

 

마이크가 아닌 음성 파일을 이용하는 경우 위와 같이 소스를 수정한다.

 

get_XXX_data()를 이용하면 오디오 데이터를 raw, wav, flac 등의 파일로 저장할 수 있다.

 

※ 참고

SpeechRecognition

 

반응형
Posted by J-sean
:

Text To Speech - gTTS

Python 2023. 4. 30. 22:26 |
반응형

파이썬에서 Google Text to Speech를 사용해 보자.

 

gTTS를 설치한다.

 

playsound를 설치한다.

playsound 1.3.0이 정상 작동 하지 않으면 1.2.2를 설치한다.

pip install playsound==1.2.2

 

소스를 입력하고 실행한다.

 

tts.mp3
0.01MB

 

※ 참고

gTTS Documentation

 

반응형
Posted by J-sean
:

MySQL(MariaDB) Connector

Python 2022. 5. 5. 00:15 |
반응형

2018.11.19 - [Python] - PyMySQL

 

Python에서 원격으로 MySQL(MariaDB)을 사용해 보자.

아래 링크를 참고해 데이터베이스를 준비한다.

2021.08.28 - [Linux] - Linux(Ubuntu) MariaDB(MySQL) Server Remote Access - 데이터베이스 원격 접속

 

mysql-connector-python을 설치한다.

 

데이터베이스에는 위와 같은 데이터를 준비한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import mysql.connector
from mysql.connector import errorcode
 
try:
    cnx = mysql.connector.connect(host="192.168.171.20", user="root",
                                  passwd="1234", database="test_db",
                                  connection_timeout=5)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    elif err.errno == 2003# 호스트 주소가 틀리거나 문제가 있다면
        print("Connection error(Timeout)")
    else:
        print(err)
else:   # 데이터베이스 접속 오류가 없다면
    cursor = cnx.cursor()
    
    query = ("SELECT * FROM test_tb")
    cursor.execute(query)
    for (id, name, age) in cursor:
        print("id: {}, name: {}, age: {}".format(id, name, age))
            
    #for row in cursor:
    #    print(row)
 
    cursor.close()
    cnx.close()
 

 

소스를 입력하고 실행한다.

 

데이터베이스의 내용이 출력된다.

 

※ 참고

MySQL Connector/Python Developer Guide

반응형
Posted by J-sean
:
반응형

Numpy 배열 평균을 구할때 축(axis)의 의미를 알아보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
data = np.array([[[1111],
                [1111],
                [1111]],
 
                [[2222],
                [2222],
                [2222]]])
 
# 2X3X4 행렬 (3행4열2그룹)
 
print(data)
print(data.shape) # (2, 3, 4)
 
print(np.mean(data, axis=0)) # 각 그룹의 같은 원소끼리 평균(3X4)
print(np.mean(data, axis=1)) # 각 그룹의 열 평균(2X4)
print(np.mean(data, axis=2)) # 각 그룹의 행 평균(2X3)
 
print(np.mean(data, axis=(12))) # 각 그룹의 평균(1X2)
 

 

 

반응형
Posted by J-sean
:
반응형

파이썬으로 이메일(Gmail)을 보내보자.


Gmail 설정 화면. IMAP 사용으로 설정되어 있다. 이메일 클라이언트 구성 설정 방법을 확인해 보자.


발신 메일(SMTP) 서버 내용을 사용한다.


Gmail은 계정 비밀번호를 그대로 사용할 수 없다. Google 계정에서 앱 비밀번호를 생성해 사용해야 한다.


'생성할 앱 - 메일', '기기 - Windows 컴퓨터'를 선택하고 생성한다.



생선된 앱 비밀번호를 복사해 둔다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import smtplib
from email.mime.text import MIMEText
 
email_from = 'your email address'
email_to = 'recipient's email address'
email_subject = 'Email Test.'
email_content = 'Sending an email test.'
 
msg = MIMEText(email_content)
msg['From'= email_from
msg ['To'= email_to
msg['Subject'= email_subject
 
smtp = smtplib.SMTP('smtp.gmail.com'587)
smtp.starttls()
smtp.login('your email address''password')
smtp.sendmail("your email address""recipient's email address", msg.as_string())
 
print(msg.as_string())
 
smtp.quit()


위 코드를 입력하고 실행한다. smtp.login()의 'password'에는 위에서 생성한 앱 비밀번호를 입력한다.


에러 없이 실행되면 이메일이 보내진다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Import smtplib for the actual sending function
import smtplib
 
# Import the email modules we'll need
from email.message import EmailMessage
 
email_from = 'your email address'
email_to = 'recipient's email address'
email_subject = 'Email Test.'
email_content = 'Sending an email test.'
 
# Create a text/plain message
msg = EmailMessage()
msg.set_content(email_content)
 
# From == the sender's email address
# To == the recipient's email address
msg['From'= email_from
msg['To'= email_to
msg['Subject'= email_subject
 
# Send the message via our own SMTP server.
smtp = smtplib.SMTP('smtp.gmail.com'587)
smtp.starttls()
smtp.login('your email address''password')
smtp.send_message(msg)
 
print(msg.as_string())
 
smtp.quit()


위 코드로도 동일하게 진행 할 수 있다.



내용은 동일하지만 실행 결과를 확인해 보면 charset이 utf-8로 설정된다는 차이가 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# And imghdr to find the types of our images
import imghdr
 
email_from = 'your email address'
email_to = 'recipient's email address'
email_cc = 'cc1 email address, cc2 email address, ...'
email_subject = 'Email Test.'
email_content = 'Sending an email test.'
 
# Create a text/plain message
msg = EmailMessage()
msg.set_content(email_content)
 
# From == the sender's email address
# To == the recipient's email address
msg['From'= email_from
msg['To'= email_to
msg['Cc'= email_cc
msg['Subject'= email_subject
 
# Open the file in binary mode. Use imghdr to figure out the MIME subtype for the image.
with open('image.png''rb') as fp:
    img_data = fp.read()
    msg.add_attachment(img_data, maintype = 'image', subtype = imghdr.what(None, img_data), filename = 'image.png')
 
# Send the message via SMTP server.
smtp = smtplib.SMTP('smtp.gmail.com'587)
smtp.starttls()
smtp.login('your email address''password')
smtp.send_message(msg)
 
smtp.quit()


이번엔 Cc(Carbon copy)와 첨부파일을 추가해 보자.


참조와 첨부파일 모두 잘 처리 되었다. (feat. Lena)


반응형
Posted by J-sean
: