audio
June 26, 2023

Запись радио

Запишем аудио-поток радиостанции из скрипта

import requests
import pyaudio
import wave
import threading
import os

class AudioRecorder:
    def __init__(self):
        self.frames = []
        self.is_recording = False
        self.stream = None

    def start(self):
        self.is_recording = True
        threading.Thread(target=self.record).start()
        print("Starting recording...")

    def stop(self):
        self.is_recording = False
        filename = self.save_to_file()
        print(f"File saved as {filename}. Size: {os.path.getsize(filename)} bytes")

    def record(self):
        CHUNK = 1024
        FORMAT = pyaudio.paInt16
        CHANNELS = 2
        RATE = 44100
        p = pyaudio.PyAudio()
        self.stream = p.open(
            format=FORMAT,
            channels=CHANNELS,
            rate=RATE,
            input=True,
            frames_per_buffer=CHUNK)
        while self.is_recording:
            data = self.stream.read(CHUNK)
            self.frames.append(data)
           # print("Recording...")
        self.stream.stop_stream()
        self.stream.close()
        p.terminate()

    def save_to_file(self):
        filename = "recording1.wav"
        wf = wave.open(filename, 'wb')
        wf.setnchannels(2)
        wf.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
        wf.setframerate(44100)
        wf.writeframes(b''.join(self.frames))
        wf.close()
        return filename

recorder = AudioRecorder()

def start_recording():
    recorder.start()

def stop_recording():
    recorder.stop()

if __name__ == '__main__':
    url = "https://icecast-vgtrk.cdnvideo.ru/vestifm_aac_64kbps"
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        print("Connected to audio stream")
        start_recording()
    else:
        print("Failed to connect to audio stream")
    input("Press Enter to stop recording...")
    stop_recording()

Список радиостанций https://espradio.ru/stream_list/