Newer
Older
Demo-Maker / modules / util / ears_sound.py
@mikado-4410 mikado-4410 on 10 Oct 2024 1 KB 最初のコミット
import cv2
import numpy as np
import pygame
import os
import modules.util.const as const


class EarsSound:
    def __init__(self, result):
        pygame.mixer.init()
        self.volume = 0.0
        self.min_volume = 0.0
        self.playing = False

        if result[0] == "none":
            self.map_image = None
            self.sound = None
        else:
            self.map_image = cv2.imread(os.path.join(const.EARS_MAP_PATH + result[0]))
            self.sound_file = os.path.join(const.EARS_SOUND_PATH + result[1])
            self.sound = pygame.mixer.Sound(self.sound_file)

    def volume_change(self, stethoscope, flag=False, type=None):
        """音量を変更する"""
        if self.map_image is None:
            return

        R, G, B = self.map_image[stethoscope[1], stethoscope[0]]
        vol = R if R != 0 else B
        VOLUME_CURVE = 9.5
        Y = pow((vol / 255.0), 1.0 / VOLUME_CURVE)
        set_volume = Y

        if set_volume > 1:
            set_volume = 1
        elif set_volume < 0:
            set_volume = 0

        if type == 1:
            set_volume = set_volume * 0.5

        self.volume = set_volume
        if flag and self.volume != 0:
            if stethoscope[0] > 195:
                self.volume = 0.1
        self.sound.set_volume(self.volume)

    def get_length(self):
        """音源の長さを秒単位で取得する"""
        if not self.sound:
            return 0

        array = pygame.sndarray.array(self.sound)
        sample_rate = pygame.mixer.get_init()[0]
        duration = array.shape[0] / float(sample_rate)
        return duration

    def set_volume(self, volume):
        """音量を設定する"""
        self.volume = volume

    def play(self):
        """音を再生する"""
        self.sound.set_volume(self.volume)
        self.sound.play(-1)

    def stop(self):
        self.sound.set_volume(self.min_volume)

    def close(self):
        """リソースを解放する"""
        pygame.mixer.quit()