Skip to content
  • Home
  • Aktuell
  • Tags
  • 0 Ungelesen 0
  • Kategorien
  • Unreplied
  • Beliebt
  • GitHub
  • Docu
  • Hilfe
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Standard: (Kein Skin)
  • Kein Skin
Einklappen
ioBroker Logo

Community Forum

donate donate
  1. ioBroker Community Home
  2. Deutsch
  3. Skripten / Logik
  4. Bräuchte untersützung bei python

NEWS

  • Jahresrückblick 2025 – unser neuer Blogbeitrag ist online! ✨
    BluefoxB
    Bluefox
    15
    1
    533

  • Neuer Blogbeitrag: Monatsrückblick - Dezember 2025 🎄
    BluefoxB
    Bluefox
    13
    1
    622

  • Weihnachtsangebot 2025! 🎄
    BluefoxB
    Bluefox
    25
    1
    1.9k

Bräuchte untersützung bei python

Geplant Angeheftet Gesperrt Verschoben Skripten / Logik
2 Beiträge 1 Kommentatoren 191 Aufrufe 2 Watching
  • Älteste zuerst
  • Neuste zuerst
  • Meiste Stimmen
Antworten
  • In einem neuen Thema antworten
Anmelden zum Antworten
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
  • A Offline
    A Offline
    AndreasE112
    schrieb am zuletzt editiert von AndreasE112
    #1

    Hi,
    ich habe folgendes vor:
    Einen Audistream per UDP empfangen und in eine Datei abspeichern.
    Ich habe dazu ein python functions code schnipsel bekommen:

    import argparse
    import pathlib
    
    from pathlib import Path
    from socketserver import BaseRequestHandler, UDPServer
    from threading import Thread
    from time import sleep, monotonic_ns
    from wave import open as wave_open
    
    try:
        from pyaudio import PyAudio
    except ModuleNotFoundError:
        PyAudio = None
    
    STREAM_CHANNELS = 1
    STREAM_WIDTH = 2
    STREAM_RATE = 16000
    
    
    def server( port, file=None, *, max_length=None, timeout=None,
                              feedback=True, daemon=False):
        """Receive data on a UDP port and record to file or play as audio.
    
        Arguments:
            port       - port number on which to listen
            file       - file to which to write; if ending in '.wav' will
                         record as audio samples; if None will play audio
            max_length - if not None, stop after this number of seconds
                         from receipt of the first datagram
            timeout    - if not None, once a datagram has been received,
                         close file and return if datagrams doesn't arrive
                         faster than this period in seconds
            feedback   - if true, print a period on standard output for
                         each 4kibytes received & diagnostics at shutdown
            daemon     - if true, re-raise keyboard exception on exit
        """
        wv = False
        if file is not None:
            file = Path(file)
            wv = file.suffix.lower() == '.wav'
    
        activity_timestamp_ns = None
        start_timestamp_ns = None
        count = 0
        exception = None
        max_length_ns = None if max_length is None \
                                            else max_length * 1000000000
        timeout_ns = None if timeout is None else timeout * 1000000000
        needs_starting = False
    
        class Handler(BaseRequestHandler):
            def handle(self):
                nonlocal activity_timestamp_ns, start_timestamp_ns
                nonlocal count, needs_starting
                if wv:
                    fh.writeframesraw(self.request[0])
                else:
                    if needs_starting:
                        needs_starting = False
                        fh.start_stream()
                    fh.write(self.request[0])
                previous_count = count
                count += len(self.request[0])
                if feedback and previous_count // 4096 != count // 4096:
                    print('.', end='', flush=True)
                activity_timestamp_ns = monotonic_ns()
                if start_timestamp_ns is None:
                    start_timestamp_ns = activity_timestamp_ns
        def read_stream():
            nonlocal exception
            with UDPServer(('0.0.0.0', int(port)), Handler) as server:
                thread = Thread(target=server.serve_forever)
                thread.start()
                try:
                    while True:
                        sleep(1)
                        now_ns = monotonic_ns()
                        if timeout_ns is not None and \
                           activity_timestamp_ns is not None and \
                           now_ns - activity_timestamp_ns > timeout_ns:
                            break
                        if max_length_ns is not None and \
                           start_timestamp_ns is not None and \
                           now_ns - start_timestamp_ns > max_length_ns:
                            break
                except KeyboardInterrupt as e:
                    exception = e
                if feedback:
                    diagnostic = ' & removing empty file' if \
                                    activity_timestamp_ns is None else ''
                    print(f'\nshutting down{diagnostic}', flush=True)
                server.shutdown()
                thread.join()
    
        if file is not None:
            with (
                wave_open(str(file), 'wb') if wv else open(file, 'wb')
            ) as fh:
                if wv:
                    fh.setnchannels(STREAM_CHANNELS)
                    fh.setsampwidth(STREAM_WIDTH)
                    fh.setframerate(STREAM_RATE)
                read_stream()
            if activity_timestamp_ns is None:
                file.unlink(missing_ok=True)
        else:
            if PyAudio:
                pya = PyAudio()
            else:
                raise ModuleNotFoundError(
                                'Install pyaudio for realtime streaming')
            needs_starting = True
            fh = pya.open(STREAM_RATE, STREAM_CHANNELS,
                pya.get_format_from_width(STREAM_WIDTH), output=True,
                start=not needs_starting
            )
            read_stream()
            fh.stop_stream()
            fh.close()
            pya.terminate()
    
        if exception and daemon:
            raise exception
    
    
    if __name__ == "__main__":
    	parser = argparse.ArgumentParser()
    	parser.add_argument("-p","--port", type=int)
    	parser.add_argument("-f","--file", type=str)
    	parser.add_argument("-l","--max_length", type=int)
    	parser.add_argument("-t","--max_timeout", type=int)
    	parser.add_argument("-fb","--feedback", type=bool)
    	parser.add_argument("-dae","--daemon", type=bool)
    	args = parser.parse_args()
    
    	temp_file = open(args.file, "w")
    	server(args.port,temp_file,args.max_length,args.max_timeout,args.feedback,args.daemon)
    

    Ich habe im prinzip nur den unteren main anteil dazugebaut.
    Ich kenne mich mit python noch nicht so gut aus. Da kommt immer diese Fehlermeldung beim aufruf:

    pi@iobroker:/opt/iobroker/iobroker-data/esphome.0 $ sudo python rec_stream_to_file.py --port 12345 --file test.wav --max_length 5  --max_timeout 1 --feedback  tr
    Traceback (most recent call last):
      File "/opt/iobroker/iobroker-data/esphome.0/rec_stream_to_file.py", line 136, in <module>
        server(args.port,temp_file,args.max_length,args.max_timeout,args.feedback,args.daemon)
    TypeError: server() takes from 1 to 2 positional arguments but 6 were given
    
    

    hat jemand ne idee was ich falsch mache ?

    ok ich hab es noch nur mit port und file versucht dann kommt eine andere meldung

    
    pi@iobroker:/opt/iobroker/iobroker-data/esphome.0 $ sudo python rec_stream_to_file.py --port 12345 --file test.wav
    Traceback (most recent call last):
      File "/opt/iobroker/iobroker-data/esphome.0/rec_stream_to_file.py", line 136, in <module>
        server(args.port,temp_file)
      File "/opt/iobroker/iobroker-data/esphome.0/rec_stream_to_file.py", line 39, in server
        file = Path(file)
               ^^^^^^^^^^
      File "/usr/lib/python3.11/pathlib.py", line 872, in __new__
        self = cls._from_parts(args)
               ^^^^^^^^^^^^^^^^^^^^^
      File "/usr/lib/python3.11/pathlib.py", line 510, in _from_parts
        drv, root, parts = self._parse_args(args)
                           ^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/lib/python3.11/pathlib.py", line 494, in _parse_args
        a = os.fspath(a)
            ^^^^^^^^^^^^
    TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper
    
    
    1 Antwort Letzte Antwort
    0
    • A Offline
      A Offline
      AndreasE112
      schrieb am zuletzt editiert von
      #2

      hat sich erledigt.. habs geschafft.

      1 Antwort Letzte Antwort
      0
      Antworten
      • In einem neuen Thema antworten
      Anmelden zum Antworten
      • Älteste zuerst
      • Neuste zuerst
      • Meiste Stimmen


      Support us

      ioBroker
      Community Adapters
      Donate

      859

      Online

      32.6k

      Benutzer

      81.9k

      Themen

      1.3m

      Beiträge
      Community
      Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
      ioBroker Community 2014-2025
      logo
      • Anmelden

      • Du hast noch kein Konto? Registrieren

      • Anmelden oder registrieren, um zu suchen
      • Erster Beitrag
        Letzter Beitrag
      0
      • Home
      • Aktuell
      • Tags
      • Ungelesen 0
      • Kategorien
      • Unreplied
      • Beliebt
      • GitHub
      • Docu
      • Hilfe