Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add save_audio_v2 function; eventually removing pyaudio. Closes #217 #241

Merged
merged 4 commits into from
Sep 5, 2023

Conversation

umesh-timalsina
Copy link
Contributor

@umesh-timalsina umesh-timalsina commented Sep 5, 2023

Test with the following script.

import struct
import uuid
from datetime import datetime
from pathlib import Path

import pyaudio
from pvrecorder import PvRecorder

from chimerapy.engine.records import AudioRecord


def list_devices(using="pvrecorder") -> None:
    if using == "pvrecorder":
        devices = PvRecorder.list_available_devices()
        for idx, device in enumerate(devices):
            print(f"Index {idx}: {device}")
    elif using == "pyaudio":     
        p = pyaudio.PyAudio()
        for i in range(p.get_device_count()):
            print(p.get_device_info_by_index(i))


def record_pv_recorder(device_index: int, record_time: int, save_path: str) -> None:
    recorder = PvRecorder(frame_length=512, device_index=device_index)

    audio_writer = AudioRecord(
        dir=Path(save_path),
        name="pvrecorder-test",
    )
    print(f"Recording for {record_time} seconds using pvrecorder.")
    recorder.start()
    start_time = datetime.now()
    while (datetime.now() - start_time).total_seconds() < record_time:
        frame = recorder.read()
        data = struct.pack("h" * len(frame), *frame)
        data_chunk = {
            "uuid": uuid.uuid4(),
            "name": "pvrecorder-test",
            "data": data,
            "dtype": "audio",
            "channels": 1,
            "sampwidth": 2,
            "framerate": recorder.sample_rate,
            "nframes": recorder.frame_length,
            "recorder_version": 2,
            "timestamp": datetime.now(),
        }
        audio_writer.write(data_chunk)

    recorder.delete()
    audio_writer.close()
    print(
        f"Finished recording for {record_time} seconds using pvrecorder. "
        f"Saved to {audio_writer.audio_file_path}"
    )


def record_pyaudio(device_index: int, record_time: int, save_path: str) -> None:
    p = pyaudio.PyAudio()
    stream = p.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=16000,
        input=True,
        frames_per_buffer=512,
        input_device_index=device_index,
        start=False,
    )

    audio_writer = AudioRecord(
        dir=Path(save_path),
        name="pyaudio-test",
    )
    print(f"Recording for {record_time} seconds using pyaudio.")
    start_time = datetime.now()
    stream.start_stream()
    while (datetime.now() - start_time).total_seconds() < record_time:
        data = stream.read(512)
        data_chunk = {
            "uuid": uuid.uuid4(),
            "name": "pyaudio-test",
            "data": data,
            "dtype": "audio",
            "channels": 1,
            "sampwidth": 2,
            "framerate": 16000,
            "nframes": 512,
            "recorder_version": 2,
            "timestamp": datetime.now(),
        }
        audio_writer.write(data_chunk)

    stream.stop_stream()
    stream.close()
    p.terminate()
    audio_writer.close()
    print(
        f"Finished recording for {record_time} seconds using pyaudio. "
        f"Saved to {audio_writer.audio_file_path}"
    )


if __name__ == "__main__":
    import sys
    from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser

    parser = ArgumentParser(
        description="Test the audio recorder in ChimeraPy.",
        formatter_class=ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument(
        "command",
        choices=["record", "list-devices"],
    )

    parser.add_argument(
        "--using",
        default="pvrecorder",
        choices=["pvrecorder", "pyaudio"],
        help="Which audio recorder to use.",
    )

    parser.add_argument(
        "--device-index",
        type=int,
        required="record" in sys.argv,
        help="Which audio device(microphone) to use.",
    )

    parser.add_argument(
        "--save-path", default=".", type=str, help="Where to save the audio file."
    )

    parser.add_argument(
        "--time", default=10, type=int, help="How long to record for(in seconds)."
    )

    args = parser.parse_args()
    if args.command == "list-devices":
        list_devices(using=args.using)
    elif args.command == "record":
        if args.using == "pvrecorder":
            record_pv_recorder(
                device_index=args.device_index,
                record_time=args.time,
                save_path=args.save_path,
            )
        elif args.using == "pyaudio":
            record_pyaudio(
                device_index=args.device_index,
                record_time=args.time,
                save_path=args.save_path,
            )

    else:
        parser.print_help()

Usage

usage: cp_audio_writer.py [-h] [--using {pvrecorder,pyaudio}] [--device-index DEVICE_INDEX] [--save-path SAVE_PATH] [--time TIME]
                          {record,list-devices}

Test the audio recorder in ChimeraPy.

positional arguments:
  {record,list-devices}

options:
  -h, --help            show this help message and exit
  --using {pvrecorder,pyaudio}
                        Which audio recorder to use. (default: pvrecorder)
  --device-index DEVICE_INDEX
                        Which audio device(microphone) to use. (default: None)
  --save-path SAVE_PATH
                        Where to save the audio file. (default: .)
  --time TIME           How long to record for(in seconds). (default: 10)

Checklist

  • Test with multiple wav files
  • Test on windows

…anized test to have all audio record tests together.
@edavalosanaya edavalosanaya merged commit 60bfe1f into main Sep 5, 2023
3 checks passed
@umesh-timalsina umesh-timalsina deleted the 217-audio-recorder-v2 branch September 6, 2023 02:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants