afrecord-win 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: afrecord-win
3
+ Version: 0.1.0
4
+ Summary: Record sound in cli in windows
5
+ Author: Sukhbinder Singh
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/sukhbinder/afrecord-win
8
+ Project-URL: Changelog, https://github.com/sukhbinder/afrecord-win/releases
9
+ Project-URL: Issues, https://github.com/sukhbinder/afrecord-win/issues
10
+ Project-URL: CI, https://github.com/sukhbinder/afrecord-win/actions
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # afrecord-win
20
+
21
+ [![PyPI](https://img.shields.io/pypi/v/afrecord-win.svg)](https://pypi.org/project/afrecord-win/)
22
+ [![Changelog](https://img.shields.io/github/v/release/sukhbinder/afrecord-win?include_prereleases&label=changelog)](https://github.com/sukhbinder/afrecord-win/releases)
23
+ [![Tests](https://github.com/sukhbinder/afrecord-win/actions/workflows/test.yml/badge.svg)](https://github.com/sukhbinder/afrecord-win/actions/workflows/test.yml)
24
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/sukhbinder/afrecord-win/blob/master/LICENSE)
25
+
26
+ Record sound in cli in windows
27
+
28
+ ## Installation
29
+
30
+ Install this tool using `pip`:
31
+ ```bash
32
+ pip install afrecord-win
33
+ ```
34
+ ## Usage
35
+
36
+ Record audio from the default microphone:
37
+ ```bash
38
+ afrecord
39
+ ```
40
+
41
+ Specify a custom output file:
42
+ ```bash
43
+ afrecord -o my_recording.wav
44
+ afrecord --output my_recording.wav
45
+ ```
46
+
47
+ For help, run:
48
+ ```bash
49
+ afrecord --help
50
+ ```
51
+
52
+ You can also use:
53
+ ```bash
54
+ python -m afrecord --help
55
+ ```
56
+
57
+ Press **Enter** or **Ctrl+C** to stop recording.
58
+ ## Development
59
+
60
+ To contribute to this tool, first checkout the code. Then create a new virtual environment:
61
+ ```bash
62
+ cd afrecord-win
63
+ python -m venv venv
64
+ source venv/bin/activate
65
+ ```
66
+ Now install the dependencies and test dependencies:
67
+ ```bash
68
+ pip install -e '.[test]'
69
+ ```
70
+ To run the tests:
71
+ ```bash
72
+ python -m pytest
73
+ ```
@@ -0,0 +1,55 @@
1
+ # afrecord-win
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/afrecord-win.svg)](https://pypi.org/project/afrecord-win/)
4
+ [![Changelog](https://img.shields.io/github/v/release/sukhbinder/afrecord-win?include_prereleases&label=changelog)](https://github.com/sukhbinder/afrecord-win/releases)
5
+ [![Tests](https://github.com/sukhbinder/afrecord-win/actions/workflows/test.yml/badge.svg)](https://github.com/sukhbinder/afrecord-win/actions/workflows/test.yml)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/sukhbinder/afrecord-win/blob/master/LICENSE)
7
+
8
+ Record sound in cli in windows
9
+
10
+ ## Installation
11
+
12
+ Install this tool using `pip`:
13
+ ```bash
14
+ pip install afrecord-win
15
+ ```
16
+ ## Usage
17
+
18
+ Record audio from the default microphone:
19
+ ```bash
20
+ afrecord
21
+ ```
22
+
23
+ Specify a custom output file:
24
+ ```bash
25
+ afrecord -o my_recording.wav
26
+ afrecord --output my_recording.wav
27
+ ```
28
+
29
+ For help, run:
30
+ ```bash
31
+ afrecord --help
32
+ ```
33
+
34
+ You can also use:
35
+ ```bash
36
+ python -m afrecord --help
37
+ ```
38
+
39
+ Press **Enter** or **Ctrl+C** to stop recording.
40
+ ## Development
41
+
42
+ To contribute to this tool, first checkout the code. Then create a new virtual environment:
43
+ ```bash
44
+ cd afrecord-win
45
+ python -m venv venv
46
+ source venv/bin/activate
47
+ ```
48
+ Now install the dependencies and test dependencies:
49
+ ```bash
50
+ pip install -e '.[test]'
51
+ ```
52
+ To run the tests:
53
+ ```bash
54
+ python -m pytest
55
+ ```
File without changes
@@ -0,0 +1,4 @@
1
+ from .cli import cli
2
+
3
+ if __name__ == "__main__":
4
+ cli()
@@ -0,0 +1,231 @@
1
+ import os
2
+ import sys
3
+ import subprocess
4
+ import tempfile
5
+ import time
6
+ import threading
7
+ from pathlib import Path
8
+
9
+
10
+ def create_powershell_script():
11
+ """Create the PowerShell script content for audio recording"""
12
+ return """
13
+ param([string]$outPath)
14
+
15
+ Add-Type @"
16
+ using System;
17
+ using System.Runtime.InteropServices;
18
+ using System.Text;
19
+ public class MciAudio {
20
+ [DllImport("winmm.dll", CharSet=CharSet.Auto)]
21
+ public static extern int mciSendString(
22
+ string command, StringBuilder buffer, int bufferSize, IntPtr callback);
23
+ }
24
+ "@
25
+
26
+ function Mci([string]$cmd) {
27
+ $buf = New-Object System.Text.StringBuilder 256
28
+ $r = [MciAudio]::mciSendString($cmd, $buf, 256, [IntPtr]::Zero)
29
+ if ($r -ne 0) {
30
+ [Console]::Error.WriteLine("MCI error $r for: $cmd")
31
+ }
32
+ return $r
33
+ }
34
+
35
+ $r = Mci "open new type waveaudio alias omp_rec"
36
+ if ($r -ne 0) { exit 1 }
37
+
38
+ Mci "set omp_rec channels 1 samplespersec 16000 bitspersample 16"
39
+
40
+ $r = Mci "record omp_rec"
41
+ if ($r -ne 0) {
42
+ Mci "close omp_rec"
43
+ exit 1
44
+ }
45
+
46
+ Write-Output "RECORDING"
47
+ [Console]::Out.Flush()
48
+
49
+ # Block until parent closes stdin or writes a line
50
+ try { [Console]::In.ReadLine() | Out-Null } catch {}
51
+
52
+ # Stop and save
53
+ Mci "stop omp_rec"
54
+ $saveCmd = 'save omp_rec "' + $outPath + '"'
55
+ $r = Mci $saveCmd
56
+ if ($r -ne 0) {
57
+ [Console]::Error.WriteLine("Save failed for: $saveCmd")
58
+ }
59
+ Mci "close omp_rec"
60
+
61
+ if (Test-Path $outPath) {
62
+ Write-Output "SAVED"
63
+ } else {
64
+ Write-Error "Output file was not created: $outPath"
65
+ exit 1
66
+ }
67
+ """
68
+
69
+
70
+ class AudioRecorder:
71
+ def __init__(self):
72
+ self.recording = False
73
+ self.process = None
74
+ self.temp_script_path = None
75
+
76
+ def start_recording(self, output_path: str) -> bool:
77
+ """Start recording audio to the specified file path"""
78
+ if self.recording:
79
+ print("Already recording")
80
+ return False
81
+
82
+ try:
83
+ # Create temporary PowerShell script
84
+ self.temp_script_path = os.path.join(
85
+ tempfile.gettempdir(), f"omp-stt-record-{int(time.time())}.ps1"
86
+ )
87
+
88
+ with open(self.temp_script_path, "w") as f:
89
+ f.write(create_powershell_script())
90
+
91
+ # Start PowerShell process
92
+ self.process = subprocess.Popen(
93
+ [
94
+ "powershell",
95
+ "-NoProfile",
96
+ "-ExecutionPolicy",
97
+ "Bypass",
98
+ "-File",
99
+ self.temp_script_path,
100
+ output_path,
101
+ ],
102
+ stdin=subprocess.PIPE,
103
+ stdout=subprocess.PIPE,
104
+ stderr=subprocess.PIPE,
105
+ text=True,
106
+ )
107
+
108
+ # Wait for recording to start (check for "RECORDING" in output)
109
+ start_time = time.time()
110
+ output = ""
111
+
112
+ while time.time() - start_time < 8:
113
+ if self.process.stdout:
114
+ line = self.process.stdout.readline()
115
+ if line:
116
+ output += line
117
+ if "RECORDING" in line:
118
+ self.recording = True
119
+ print("Recording started")
120
+ return True
121
+
122
+ # Check if process exited
123
+ if self.process.poll() is not None:
124
+ break
125
+
126
+ if not self.recording:
127
+ # Process failed to start properly
128
+ stderr_output = ""
129
+ if self.process.stderr:
130
+ stderr_output = self.process.stderr.read()
131
+ print(f"PowerShell recording failed to start: {stderr_output}")
132
+ self.cleanup()
133
+ return False
134
+
135
+ except Exception as e:
136
+ print(f"Error starting recording: {e}")
137
+ self.cleanup()
138
+ return False
139
+
140
+ return True
141
+
142
+ def stop_recording(self) -> bool:
143
+ """Stop the current recording"""
144
+ if not self.recording or not self.process:
145
+ print("Not currently recording")
146
+ return False
147
+
148
+ try:
149
+ # Send stop command to PowerShell script
150
+ if self.process.stdin:
151
+ self.process.stdin.write("stop\n")
152
+ self.process.stdin.flush()
153
+ self.process.stdin.close()
154
+
155
+ # Wait for process to finish with timeout
156
+ timeout = 8
157
+ start_time = time.time()
158
+
159
+ while self.process.poll() is None and (time.time() - start_time) < timeout:
160
+ time.sleep(0.1)
161
+
162
+ if self.process.poll() is None:
163
+ # Force kill if still running
164
+ self.process.kill()
165
+ self.process.wait()
166
+
167
+ # Clean up temp script
168
+ self.cleanup()
169
+
170
+ print("Recording stopped")
171
+ return True
172
+
173
+ except Exception as e:
174
+ print(f"Error stopping recording: {e}")
175
+ self.cleanup()
176
+ return False
177
+
178
+ def cleanup(self):
179
+ """Clean up temporary files and processes"""
180
+ try:
181
+ if self.temp_script_path and os.path.exists(self.temp_script_path):
182
+ os.remove(self.temp_script_path)
183
+ except:
184
+ pass
185
+
186
+ self.recording = False
187
+ self.process = None
188
+
189
+
190
+ def main():
191
+ """Main function to demonstrate the recorder"""
192
+ if len(sys.argv) != 2:
193
+ print("Usage: python powershell_record.py <output_file.wav>")
194
+ sys.exit(1)
195
+
196
+ output_file = sys.argv[1]
197
+
198
+ # Create recorder instance
199
+ recorder = AudioRecorder()
200
+
201
+ try:
202
+ print(f"Starting recording to {output_file}")
203
+
204
+ # Start recording
205
+ if not recorder.start_recording(output_file):
206
+ print("Failed to start recording")
207
+ sys.exit(1)
208
+
209
+ # Wait for user input to stop
210
+ input("Press Enter to stop recording...")
211
+
212
+ # Stop recording
213
+ recorder.stop_recording()
214
+
215
+ # Verify file exists and has content
216
+ if os.path.exists(output_file):
217
+ size = os.path.getsize(output_file)
218
+ print(f"Recording saved: {output_file} ({size} bytes)")
219
+ else:
220
+ print("Recording file was not created")
221
+
222
+ except KeyboardInterrupt:
223
+ print("\nStopping recording...")
224
+ recorder.stop_recording()
225
+ except Exception as e:
226
+ print(f"Error: {e}")
227
+ recorder.stop_recording()
228
+
229
+
230
+ if __name__ == "__main__":
231
+ main()
@@ -0,0 +1,65 @@
1
+ """CLI interface for afrecord-win."""
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+ from .afrecordmain import AudioRecorder
7
+
8
+
9
+ def create_parser() -> argparse.ArgumentParser:
10
+ """Create the argument parser for the CLI."""
11
+ parser = argparse.ArgumentParser(
12
+ prog="afrecord",
13
+ description="Record sound from the command line on Windows.",
14
+ )
15
+ parser.add_argument(
16
+ "-o",
17
+ "--output",
18
+ dest="output_file",
19
+ default="output.wav",
20
+ help="Output WAV file path (default: output.wav)",
21
+ )
22
+ return parser
23
+
24
+
25
+ def cli() -> None:
26
+ """Main CLI entry point."""
27
+ parser = create_parser()
28
+ args = parser.parse_args()
29
+
30
+ recorder = AudioRecorder()
31
+
32
+ try:
33
+ print(f"Starting recording to {args.output_file}")
34
+
35
+ if not recorder.start_recording(args.output_file):
36
+ print("Failed to start recording", file=sys.stderr)
37
+ sys.exit(1)
38
+
39
+ print("Recording... Press Enter to stop")
40
+
41
+ input()
42
+
43
+ recorder.stop_recording()
44
+
45
+ if os.path.exists(args.output_file):
46
+ size = os.path.getsize(args.output_file)
47
+ print(f"Recording saved: {args.output_file} ({size} bytes)")
48
+ else:
49
+ print("Recording file was not created", file=sys.stderr)
50
+ sys.exit(1)
51
+
52
+ except KeyboardInterrupt:
53
+ print("\nStopping recording...")
54
+ recorder.stop_recording()
55
+
56
+ if os.path.exists(args.output_file):
57
+ size = os.path.getsize(args.output_file)
58
+ print(f"Recording saved: {args.output_file} ({size} bytes)")
59
+ else:
60
+ print("Recording file was not created", file=sys.stderr)
61
+ sys.exit(1)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ cli()
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: afrecord-win
3
+ Version: 0.1.0
4
+ Summary: Record sound in cli in windows
5
+ Author: Sukhbinder Singh
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/sukhbinder/afrecord-win
8
+ Project-URL: Changelog, https://github.com/sukhbinder/afrecord-win/releases
9
+ Project-URL: Issues, https://github.com/sukhbinder/afrecord-win/issues
10
+ Project-URL: CI, https://github.com/sukhbinder/afrecord-win/actions
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # afrecord-win
20
+
21
+ [![PyPI](https://img.shields.io/pypi/v/afrecord-win.svg)](https://pypi.org/project/afrecord-win/)
22
+ [![Changelog](https://img.shields.io/github/v/release/sukhbinder/afrecord-win?include_prereleases&label=changelog)](https://github.com/sukhbinder/afrecord-win/releases)
23
+ [![Tests](https://github.com/sukhbinder/afrecord-win/actions/workflows/test.yml/badge.svg)](https://github.com/sukhbinder/afrecord-win/actions/workflows/test.yml)
24
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/sukhbinder/afrecord-win/blob/master/LICENSE)
25
+
26
+ Record sound in cli in windows
27
+
28
+ ## Installation
29
+
30
+ Install this tool using `pip`:
31
+ ```bash
32
+ pip install afrecord-win
33
+ ```
34
+ ## Usage
35
+
36
+ Record audio from the default microphone:
37
+ ```bash
38
+ afrecord
39
+ ```
40
+
41
+ Specify a custom output file:
42
+ ```bash
43
+ afrecord -o my_recording.wav
44
+ afrecord --output my_recording.wav
45
+ ```
46
+
47
+ For help, run:
48
+ ```bash
49
+ afrecord --help
50
+ ```
51
+
52
+ You can also use:
53
+ ```bash
54
+ python -m afrecord --help
55
+ ```
56
+
57
+ Press **Enter** or **Ctrl+C** to stop recording.
58
+ ## Development
59
+
60
+ To contribute to this tool, first checkout the code. Then create a new virtual environment:
61
+ ```bash
62
+ cd afrecord-win
63
+ python -m venv venv
64
+ source venv/bin/activate
65
+ ```
66
+ Now install the dependencies and test dependencies:
67
+ ```bash
68
+ pip install -e '.[test]'
69
+ ```
70
+ To run the tests:
71
+ ```bash
72
+ python -m pytest
73
+ ```
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ afrecord_win/__init__.py
5
+ afrecord_win/__main__.py
6
+ afrecord_win/afrecordmain.py
7
+ afrecord_win/cli.py
8
+ afrecord_win.egg-info/PKG-INFO
9
+ afrecord_win.egg-info/SOURCES.txt
10
+ afrecord_win.egg-info/dependency_links.txt
11
+ afrecord_win.egg-info/entry_points.txt
12
+ afrecord_win.egg-info/requires.txt
13
+ afrecord_win.egg-info/top_level.txt
14
+ tests/test_afrecord_win.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ afrecord = afrecord_win.cli:cli
@@ -0,0 +1,3 @@
1
+
2
+ [test]
3
+ pytest
@@ -0,0 +1 @@
1
+ afrecord_win
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "afrecord-win"
3
+ version = "0.1.0"
4
+ description = "Record sound in cli in windows"
5
+ readme = "README.md"
6
+ authors = [{name = "Sukhbinder Singh"}]
7
+ license = {text = "Apache-2.0"}
8
+ requires-python = ">=3.8"
9
+ classifiers = [
10
+ "License :: OSI Approved :: Apache Software License"
11
+ ]
12
+ dependencies = []
13
+
14
+ [project.urls]
15
+ Homepage = "https://github.com/sukhbinder/afrecord-win"
16
+ Changelog = "https://github.com/sukhbinder/afrecord-win/releases"
17
+ Issues = "https://github.com/sukhbinder/afrecord-win/issues"
18
+ CI = "https://github.com/sukhbinder/afrecord-win/actions"
19
+
20
+ [project.scripts]
21
+ afrecord = "afrecord_win.cli:cli"
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest"]
25
+
26
+ [build-system]
27
+ requires = ["setuptools", "wheel"]
28
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,279 @@
1
+ """Tests for afrecord-win package."""
2
+
3
+ import os
4
+ import sys
5
+ import tempfile
6
+ import pytest
7
+ from unittest.mock import patch, MagicMock
8
+
9
+ from afrecord_win import cli
10
+ from afrecord_win.afrecordmain import AudioRecorder, create_powershell_script
11
+
12
+
13
+ class TestCreateParser:
14
+ """Tests for the CLI argument parser."""
15
+
16
+ def test_create_parser_returns_argument_parser(self):
17
+ """Test that create_parser returns an ArgumentParser instance."""
18
+ parser = cli.create_parser()
19
+ assert parser is not None
20
+
21
+ def test_parser_default_output_file(self):
22
+ """Test parser default output file is output.wav."""
23
+ parser = cli.create_parser()
24
+ args = parser.parse_args([])
25
+ assert args.output_file == "output.wav"
26
+
27
+ def test_parser_custom_output_file_short_option(self):
28
+ """Test parser accepts custom output file with -o option."""
29
+ parser = cli.create_parser()
30
+ args = parser.parse_args(["-o", "custom.wav"])
31
+ assert args.output_file == "custom.wav"
32
+
33
+ def test_parser_custom_output_file_long_option(self):
34
+ """Test parser accepts custom output file with --output option."""
35
+ parser = cli.create_parser()
36
+ args = parser.parse_args(["--output", "recording.wav"])
37
+ assert args.output_file == "recording.wav"
38
+
39
+
40
+ class TestAudioRecorder:
41
+ """Tests for the AudioRecorder class."""
42
+
43
+ def test_recorder_initial_state(self):
44
+ """Test AudioRecorder initializes with correct state."""
45
+ recorder = AudioRecorder()
46
+ assert recorder.recording is False
47
+ assert recorder.process is None
48
+ assert recorder.temp_script_path is None
49
+
50
+ def test_cleanup_removes_temp_script(self):
51
+ """Test cleanup removes temporary script file."""
52
+ recorder = AudioRecorder()
53
+ # Create a temp file to simulate
54
+ with tempfile.NamedTemporaryFile(delete=False) as tmp:
55
+ recorder.temp_script_path = tmp.name
56
+
57
+ recorder.cleanup()
58
+
59
+ assert not os.path.exists(recorder.temp_script_path)
60
+ assert recorder.recording is False
61
+ assert recorder.process is None
62
+
63
+ def test_cleanup_handles_missing_temp_script(self):
64
+ """Test cleanup handles missing temp script gracefully."""
65
+ recorder = AudioRecorder()
66
+ recorder.temp_script_path = "/nonexistent/path/script.ps1"
67
+ # Should not raise an exception
68
+ recorder.cleanup()
69
+
70
+ @patch("afrecord_win.afrecordmain.subprocess.Popen")
71
+ @patch("afrecord_win.afrecordmain.os.path.exists")
72
+ @patch("afrecord_win.afrecordmain.open")
73
+ def test_start_recording_creates_process(
74
+ self, mock_open, mock_exists, mock_popen
75
+ ):
76
+ """Test start_recording creates a PowerShell subprocess."""
77
+ mock_exists.return_value = False
78
+ mock_process = MagicMock()
79
+ mock_process.stdout.readline.return_value = "RECORDING\n"
80
+ mock_process.poll.return_value = None
81
+ mock_popen.return_value = mock_process
82
+
83
+ recorder = AudioRecorder()
84
+ result = recorder.start_recording("test.wav")
85
+
86
+ assert mock_popen.called
87
+ assert result is True
88
+ recorder.cleanup()
89
+
90
+ @patch("afrecord_win.afrecordmain.subprocess.Popen")
91
+ @patch("afrecord_win.afrecordmain.os.path.exists")
92
+ def test_start_recording_returns_false_when_already_recording(
93
+ self, mock_exists, mock_popen
94
+ ):
95
+ """Test start_recording returns False if already recording."""
96
+ mock_exists.return_value = False
97
+ recorder = AudioRecorder()
98
+ recorder.recording = True
99
+
100
+ result = recorder.start_recording("test.wav")
101
+
102
+ assert result is False
103
+ assert not mock_popen.called
104
+
105
+ @patch("afrecord_win.afrecordmain.subprocess.Popen")
106
+ @patch("afrecord_win.afrecordmain.os.path.exists")
107
+ def test_stop_recording_returns_false_when_not_recording(
108
+ self, mock_exists, mock_popen
109
+ ):
110
+ """Test stop_recording returns False if not recording."""
111
+ mock_exists.return_value = False
112
+ recorder = AudioRecorder()
113
+
114
+ result = recorder.stop_recording()
115
+
116
+ assert result is False
117
+
118
+ @patch("afrecord_win.afrecordmain.subprocess.Popen")
119
+ @patch("afrecord_win.afrecordmain.os.path.exists")
120
+ def test_stop_recording_sends_stop_command(
121
+ self, mock_exists, mock_popen
122
+ ):
123
+ """Test stop_recording sends stop command to process."""
124
+ mock_exists.return_value = False
125
+ mock_process = MagicMock()
126
+ mock_process.poll.return_value = 0
127
+ mock_process.stdin = MagicMock()
128
+ mock_popen.return_value = mock_process
129
+
130
+ recorder = AudioRecorder()
131
+ # First start recording
132
+ mock_process.stdout.readline.return_value = "RECORDING\n"
133
+ recorder.start_recording("test.wav")
134
+ # Then stop
135
+ result = recorder.stop_recording()
136
+
137
+ assert mock_process.stdin.write.called
138
+ assert result is True
139
+
140
+
141
+ class TestPowerShellScript:
142
+ """Tests for PowerShell script generation."""
143
+
144
+ def test_create_powershell_script_returns_string(self):
145
+ """Test create_powershell_script returns a string."""
146
+ script = create_powershell_script()
147
+ assert isinstance(script, str)
148
+
149
+ def test_create_powershell_script_contains_required_commands(self):
150
+ """Test generated script contains required MCI commands."""
151
+ script = create_powershell_script()
152
+ assert "open new type waveaudio" in script
153
+ assert "record omp_rec" in script
154
+ assert "stop omp_rec" in script
155
+ assert "save omp_rec" in script
156
+ assert "close omp_rec" in script
157
+
158
+ def test_create_powershell_script_has_parameter(self):
159
+ """Test generated script accepts outPath parameter."""
160
+ script = create_powershell_script()
161
+ assert "param([string]$outPath)" in script
162
+
163
+ def test_create_powershell_script_has_error_handling(self):
164
+ """Test generated script includes error handling."""
165
+ script = create_powershell_script()
166
+ assert "Write-Error" in script or "exit 1" in script
167
+
168
+
169
+ class TestCLI:
170
+ """Tests for CLI function."""
171
+
172
+ @patch("afrecord_win.cli.os.path.exists")
173
+ @patch("afrecord_win.cli.os.path.getsize")
174
+ @patch("afrecord_win.cli.AudioRecorder")
175
+ @patch("afrecord_win.cli.create_parser")
176
+ def test_cli_success(
177
+ self, mock_create_parser, mock_recorder_class, mock_getsize, mock_exists
178
+ ):
179
+ """Test CLI successful recording flow."""
180
+ mock_exists.return_value = True
181
+ mock_getsize.return_value = 1024
182
+
183
+ mock_recorder = MagicMock()
184
+ mock_recorder.start_recording.return_value = True
185
+ mock_recorder_class.return_value = mock_recorder
186
+
187
+ mock_parser = MagicMock()
188
+ mock_parser.parse_args.return_value = MagicMock(output_file="test.wav")
189
+ mock_create_parser.return_value = mock_parser
190
+
191
+ with patch("afrecord_win.cli.input", side_effect=[""]):
192
+ cli.cli()
193
+
194
+ mock_recorder.start_recording.assert_called_once_with("test.wav")
195
+ mock_recorder.stop_recording.assert_called_once()
196
+
197
+ @patch("afrecord_win.cli.os.path.exists")
198
+ @patch("afrecord_win.cli.AudioRecorder")
199
+ @patch("afrecord_win.cli.create_parser")
200
+ def test_cli_start_failure(
201
+ self, mock_create_parser, mock_recorder_class, mock_exists, capsys
202
+ ):
203
+ """Test CLI handles start recording failure."""
204
+ mock_exists.return_value = False
205
+ mock_recorder = MagicMock()
206
+ mock_recorder.start_recording.return_value = False
207
+ mock_recorder_class.return_value = mock_recorder
208
+
209
+ mock_parser = MagicMock()
210
+ mock_parser.parse_args.return_value = MagicMock(output_file="test.wav")
211
+ mock_create_parser.return_value = mock_parser
212
+
213
+ with pytest.raises(SystemExit) as exc_info:
214
+ cli.cli()
215
+
216
+ assert exc_info.value.code == 1
217
+
218
+
219
+ @pytest.mark.skipif(sys.platform != "win32", reason="Requires Windows")
220
+ class TestIntegrationWindows:
221
+ """Integration tests that only run on Windows."""
222
+
223
+ def test_audio_recorder_real_instance(self):
224
+ """Test AudioRecorder can be instantiated on Windows."""
225
+ recorder = AudioRecorder()
226
+ assert recorder is not None
227
+ assert recorder.recording is False
228
+
229
+ def test_powershell_script_execution(self, tmp_path):
230
+ """Test PowerShell script can be created and is valid."""
231
+ script_content = create_powershell_script()
232
+
233
+ # Write script to temp file
234
+ script_file = tmp_path / "test_record.ps1"
235
+ script_file.write_text(script_content)
236
+
237
+ # Verify script exists and has content
238
+ assert script_file.exists()
239
+ assert script_file.stat().st_size > 0
240
+
241
+ # Try to execute PowerShell with the script (syntax check)
242
+ import subprocess
243
+
244
+ result = subprocess.run(
245
+ ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script_file), "-outPath", str(tmp_path / "test.wav")],
246
+ capture_output=True,
247
+ text=True,
248
+ timeout=5
249
+ )
250
+
251
+ # Script should either start recording or fail gracefully
252
+ # We're just testing it can be invoked
253
+ assert result is not None
254
+
255
+ def test_full_recording_workflow(self, tmp_path):
256
+ """Test complete recording workflow on Windows."""
257
+ output_file = tmp_path / "integration_test.wav"
258
+ recorder = AudioRecorder()
259
+
260
+ try:
261
+ # Start recording
262
+ started = recorder.start_recording(str(output_file))
263
+
264
+ if started:
265
+ # Immediately stop (short recording)
266
+ import time
267
+ time.sleep(0.5)
268
+ recorder.stop_recording()
269
+
270
+ # Verify file was created
271
+ # Note: This may fail if no microphone is available
272
+ if output_file.exists():
273
+ assert output_file.stat().st_size > 0
274
+ except Exception:
275
+ # Recording may fail in headless environments
276
+ # This is expected in CI/CD without audio hardware
277
+ pytest.skip("No audio hardware available")
278
+ finally:
279
+ recorder.cleanup()