Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. Bräuchte untersützung bei python

    NEWS

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    • Monatsrückblick - April 2025

    Bräuchte untersützung bei python

    This topic has been deleted. Only users with topic management privileges can see it.
    • A
      AndreasE112 last edited by AndreasE112

      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 Reply Last reply Reply Quote 0
      • A
        AndreasE112 last edited by

        hat sich erledigt.. habs geschafft.

        1 Reply Last reply Reply Quote 0
        • First post
          Last post

        Support us

        ioBroker
        Community Adapters
        Donate

        941
        Online

        31.7k
        Users

        79.7k
        Topics

        1.3m
        Posts

        1
        2
        89
        Loading More Posts
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes
        Reply
        • Reply as topic
        Log in to reply
        Community
        Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
        The ioBroker Community 2014-2023
        logo