# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: JHC
@license: None
@contact: [email protected]
@file: test.py
@time: 2022/11/26/ 00:09
@desc:
"""
import os
import time
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
import platform
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import applescript
import playsound
from threading import Thread
import random
def get_volume_object():
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
return volume
def change_volume(volume):
"""
强制修改电脑音量 94%
缺点:
音量100% 时直接点击静音,不会自动取消静音
"""
now_volume = volume.GetMasterVolumeLevel()
if now_volume != 0:
volume.SetMute(0, None)
volume.SetMasterVolumeLevel(-1, None)
def get_system():
"""
获取系统类型
"""
return platform.system()
def play_voice():
"""
播放音频
"""
name_list = os.listdir("./res")
while True:
name = random.choice(name_list)
filename = './res/{}'.format(name)
playsound.playsound(filename, True)
time.sleep(1)
def keep_voice(volume):
"""
强制修改音量
"""
while True:
change_volume(volume)
time.sleep(1)
def run():
# speak()
system = get_system()
volume = get_volume_object()
if system.lower() == "windows":
change_volume(volume)
elif system.lower() == "mac":
applescript.run('set volume output volume 100')
else:
pass
try:
Thread(target=play_voice).start()
Thread(target=keep_voice, args=(volume,)).start()
except:
os._exit(0)
if __name__ == '__main__':
run()
res文件夹下放MP3格式音频文件
程序运行后会后台随机播放res文件夹下的MP3文件,并且强制修改电脑音量为94%
win版本程序下载链接:
https://jhc001.lanzoub.com/ivOax0gwy1ze