-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio.py
187 lines (147 loc) · 6.29 KB
/
audio.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import time
import os
import sys
from datetime import datetime
import pyaudio
import numpy as np
from obswebsocket import obsws, requests
# OBS WebSocket configuration
obs_host = "localhost"
obs_port = 4444
obs_password = "your_obs_password"
# Connect to OBS WebSocket
obs_ws = obsws(obs_host, obs_port, obs_password)
obs_ws.connect()
# Audio settings
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
THRESHOLD = 0.02 # Threshold for music detection
# Function to create a log file
def create_log(log_path):
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
log_filename = os.path.join(log_path, f"OBS_audio_control_log_{timestamp}.txt")
with open(log_filename, "w") as log_file:
log_file.write("Log file created.\n")
return log_filename
# Function to write to the log file
def write_to_log(log_filename, message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(log_filename, "a") as log_file:
log_file.write(f"{timestamp} - {message}\n")
# Function to switch audio source and play music in OBS
def switch_and_play_music():
obs_ws.call(requests.SetCurrentScene(sceneName="Your Scene Name"))
obs_ws.call(requests.SetMute(mute=True, source="Your Source Name")) # Mute original audio source
obs_ws.call(requests.SetSourceRender(source="Your Source Name", render=False)) # Disable original audio source
obs_ws.call(requests.SetSourceRender(source="Your New Source Name", render=True)) # Enable new audio source
obs_ws.call(requests.PlayPauseMedia(source="Your Music File")) # Play music file
# Function to switch back audio source in OBS
def switch_back_audio():
obs_ws.call(requests.SetCurrentScene(sceneName="Your Scene Name"))
obs_ws.call(requests.SetMute(mute=False, source="Your Source Name")) # Unmute original audio source
obs_ws.call(requests.SetSourceRender(source="Your Source Name", render=True)) # Enable original audio source
obs_ws.call(requests.SetSourceRender(source="Your New Source Name", render=False)) # Disable new audio source
# Function to stop audio monitoring
def stop_audio_monitoring(p, stream):
if stream:
stream.stop_stream()
stream.close()
if p:
p.terminate()
# Monitoring 1: Ambient microphone monitoring
def monitoring_1(log_filename):
status_display("Ambient microphone monitoring")
write_to_log(log_filename, "Ambient microphone monitoring")
time.sleep(5)
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
while True:
data = stream.read(CHUNK)
audio_data = np.frombuffer(data, dtype=np.int16)
rms = np.sqrt(np.mean(np.square(audio_data)))
if rms > THRESHOLD:
status_display("Music detected!")
write_to_log(log_filename, "Music detected!")
switch_and_play_music()
break
stop_audio_monitoring(p, stream)
monitoring_2(log_filename)
# Monitoring 2: Waiting for music to stop
def monitoring_2(log_filename):
status_display("Waiting for the music in the Ambient microphone to stop")
write_to_log(log_filename, "Waiting for the music in the Ambient microphone to stop")
time.sleep(5)
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
while True:
data = stream.read(CHUNK)
audio_data = np.frombuffer(data, dtype=np.int16)
rms = np.sqrt(np.mean(np.square(audio_data)))
if rms < THRESHOLD:
status_display("Music stopped")
write_to_log(log_filename, "Music stopped")
switch_back_audio()
break
stop_audio_monitoring(p, stream)
monitoring_1(log_filename)
# Function to display specific information in a status box
def status_display(message):
os.system('cls' if os.name == 'nt' else 'clear')
print("Enter 'start' to start monitoring, enter 'stop' to stop monitoring, enter 'exit' to exit.")
print(message)
# System module
def system_module():
print("Enter 'start' to start monitoring, enter 'stop' to stop monitoring, enter 'exit' to exit.")
time.sleep(5) # Wait for 5 seconds before starting monitoring
log_path = "/path/to/log/directory" # Specify the log file path here
log_filename = create_log(log_path)
status_display("On standby...")
p = None
stream = None
while True:
command = input("Enter command: ")
if command == "start":
status_display("Starting monitoring...")
stop_audio_monitoring(p, stream)
time.sleep(1)
monitoring_1(log_filename)
elif command == "stop":
status_display("Stopping monitoring...")
write_to_log(log_filename, "Monitoring stopped.")
time.sleep(1)
stop_audio_monitoring(p, stream)
time.sleep(1)
status_display("On standby...")
break
elif command == "exit":
status_display("Exiting program...")
write_to_log(log_filename, "Program exited.")
time.sleep(1)
stop_audio_monitoring(p, stream)
time.sleep(1)
obs_ws.disconnect()
time.sleep(1)
sys.exit()
# Entry point of the program
if __name__ == "__main__":
system_module()
# Make sure you have the appropriate python 3 environment deployed on your computer.
# Make sure you have installed the required libraries using the following command.
# Enter in macOS Terminal: 'pip install pyaudio librosa obs-websocket-py numpy'
# Make sure OBS is running and the WebSocket plugin is enabled.
# Make sure the password is set correctly in the code (obs_password).
# Replace the placeholder strings "Your Scene Name", "Your Source Name", "Your New Source Name",
# and "Your Music File" with the appropriate names from your OBS settings.
# Replace the placeholder string "/path/to/log/directory" with the location where you want to save the logs.
# In addition, please confirm the numerical size of the ‘THRESHOLD’ parameter through debugging.
# This number will affect the sensitivity of the program to cut off the live audio.