-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinux_basic.py
More file actions
236 lines (193 loc) · 6.79 KB
/
linux_basic.py
File metadata and controls
236 lines (193 loc) · 6.79 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env python3
"""
Linux PulseAudio capture example.
This example demonstrates how to capture audio from a specific process on Linux
using ProcTap with PulseAudio backend.
Requirements:
- Linux with PulseAudio or PipeWire (with pulseaudio-compat)
- pulsectl library: pip install pulsectl
- parec command: sudo apt-get install pulseaudio-utils
Usage:
python linux_pulse_basic.py --pid 12345 --duration 5 --output output.wav
python linux_pulse_basic.py --name firefox --duration 10 --output firefox.wav
Note:
The target process must be actively playing audio when you run this script.
"""
from __future__ import annotations
import argparse
import sys
import wave
import time
from pathlib import Path
try:
from proctap import ProcessAudioCapture, StreamConfig
except ImportError:
print("Error: proctap is not installed. Install it with: pip install proc-tap")
sys.exit(1)
def find_pid_by_name(process_name: str) -> int:
"""
Find PID by process name.
Args:
process_name: Process name to search for
Returns:
Process ID
Raises:
RuntimeError: If process not found or psutil not available
"""
try:
import psutil
except ImportError:
raise RuntimeError(
"psutil is required to find process by name. "
"Install it with: pip install psutil"
)
# Find processes with matching name
matching_pids = []
for proc in psutil.process_iter(['pid', 'name']):
try:
if process_name.lower() in proc.info['name'].lower():
matching_pids.append((proc.info['pid'], proc.info['name']))
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
if not matching_pids:
raise RuntimeError(f"No process found with name containing '{process_name}'")
if len(matching_pids) > 1:
print(f"Found {len(matching_pids)} matching processes:")
for pid, name in matching_pids:
print(f" PID {pid}: {name}")
print(f"\nUsing first match: PID {matching_pids[0][0]}")
return matching_pids[0][0]
def main() -> int:
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Capture audio from a specific process on Linux using PulseAudio"
)
# Process selection (mutually exclusive)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'--pid',
type=int,
help='Process ID to capture audio from'
)
group.add_argument(
'--name',
type=str,
help='Process name to search for (requires psutil)'
)
# Output options
parser.add_argument(
'--output', '-o',
type=str,
default='output.wav',
help='Output WAV file path (default: output.wav)'
)
parser.add_argument(
'--duration', '-d',
type=float,
default=5.0,
help='Recording duration in seconds (default: 5.0)'
)
# Audio format options
parser.add_argument(
'--sample-rate', '-r',
type=int,
default=44100,
help='Sample rate in Hz (default: 44100)'
)
parser.add_argument(
'--channels', '-c',
type=int,
default=2,
choices=[1, 2],
help='Number of channels: 1 (mono) or 2 (stereo) (default: 2)'
)
args = parser.parse_args()
# Determine PID
try:
if args.name:
print(f"Searching for process: {args.name}")
pid = find_pid_by_name(args.name)
print(f"Found PID: {pid}")
else:
pid = args.pid
print(f"Using PID: {pid}")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
return 1
# Create output directory if needed
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
# Prepare WAV file
wav_file = wave.open(str(output_path), 'wb')
wav_file.setnchannels(args.channels)
wav_file.setsampwidth(2) # 16-bit PCM
wav_file.setframerate(args.sample_rate)
frame_count = 0
def on_audio_data(pcm_data: bytes, frames: int) -> None:
"""Callback function to write audio data to WAV file."""
nonlocal frame_count
wav_file.writeframes(pcm_data)
frame_count += len(pcm_data) // (args.channels * 2)
try:
print("\n" + "=" * 60)
print("Linux PulseAudio Audio Capture")
print("=" * 60)
print(f"Target PID: {pid}")
print(f"Output file: {output_path}")
print(f"Duration: {args.duration} seconds")
print(f"Sample rate: {args.sample_rate} Hz")
print(f"Channels: {args.channels}")
print("=" * 60)
# Create stream configuration
config = StreamConfig(
sample_rate=args.sample_rate,
channels=args.channels,
)
# Create audio capture instance
print("\nInitializing ProcTap...")
tap = ProcessAudioCapture(pid=pid, config=config, on_data=on_audio_data)
print("Starting audio capture...")
print("\n⚠️ IMPORTANT: Make sure the target process is actively playing audio!")
print("⚠️ The capture may fail if the process is not producing audio.\n")
tap.start()
# Record for specified duration
print(f"Recording for {args.duration} seconds...")
time.sleep(args.duration)
# Stop capture
print("\nStopping capture...")
tap.stop()
tap.close()
# Close WAV file
wav_file.close()
# Show results
duration = frame_count / args.sample_rate
file_size = output_path.stat().st_size
print("\n" + "=" * 60)
print("Capture Complete!")
print("=" * 60)
print(f"Frames captured: {frame_count:,}")
print(f"Duration: {duration:.2f} seconds")
print(f"File size: {file_size:,} bytes ({file_size / 1024:.1f} KB)")
print(f"Output file: {output_path.absolute()}")
print("=" * 60)
if frame_count == 0:
print("\n⚠️ WARNING: No audio data was captured!")
print(" Possible reasons:")
print(" - The process is not currently playing audio")
print(" - The process does not have PulseAudio streams")
print(" - Permission issues")
print("\n Try:")
print(" 1. Make sure the process is actively playing audio")
print(" 2. Check 'pactl list sink-inputs' to see active streams")
return 1
return 0
except KeyboardInterrupt:
print("\n\nInterrupted by user")
wav_file.close()
return 130
except Exception as e:
print(f"\nError during capture: {e}", file=sys.stderr)
wav_file.close()
return 1
if __name__ == '__main__':
sys.exit(main())