
    g6                         d Z ddlZddlZddlZddlZddlmZ ddlm	Z	 ddl
mZ ddlmZmZ ddlmZ  G d d	e      Z G d
 de      Z G d de      Zd Zy)zImplements AudioClip (base class for audio clips) and its main subclasses:

- Audio clips: AudioClip, AudioFileClip, AudioArrayClip
- Composition: CompositeAudioClip
    N)ffmpeg_audiowriteffplay_audiopreview)Clip)convert_path_to_stringrequires_duration)extensions_dictc                        e Zd ZdZd
 fd	Ze	 	 	 	 	 	 dd       Ze	 dd       ZddZe e	d      	 	 	 	 	 	 	 	 dd              Z
e	 dd       Z fd	Z xZS )	AudioClipa  Base class for audio clips.

    See ``AudioFileClip`` and ``CompositeAudioClip`` for usable classes.

    An AudioClip is a Clip with a ``frame_function``  attribute of
    the form `` t -> [ f_t ]`` for mono sound and
    ``t-> [ f1_t, f2_t ]`` for stereo sound (the arrays are Numpy arrays).
    The `f_t` are floats between -1 and 1. These bounds can be
    trespassed without problems (the program will put the
    sound back into the bounds at conversion time, without much impact).

    Parameters
    ----------

    frame_function
      A function `t-> frame at time t`. The frame does not mean much
      for a sound, it is just a float. What 'makes' the sound are
      the variations of that float in the time.

    duration
      Duration of the clip (in seconds). Some clips are infinite, in
      this case their duration will be ``None``.

    nchannels
      Number of channels (one or two for mono or stereo).

    Examples
    --------

    .. code:: python

        # Plays the note A in mono (a sine wave of frequency 440 Hz)
        import numpy as np
        frame_function = lambda t: np.sin(440 * 2 * np.pi * t)
        clip = AudioClip(frame_function, duration=5, fps=44100)
        clip.preview()

        # Plays the note A in stereo (two sine waves of frequencies 440 and 880 Hz)
        frame_function = lambda t: np.array([
            np.sin(440 * 2 * np.pi * t),
            np.sin(880 * 2 * np.pi * t)
        ]).T.copy(order="C")
        clip = AudioClip(frame_function, duration=3, fps=44100)
        clip.preview()

    c                     t         |           ||| _        |E|| _        | j	                  d      }t        |d      rt        t        |            | _        nd| _        ||| _	        || _
        y y )Nr   __iter__   )super__init__fpsframe_function	get_framehasattrlenlist	nchannelsdurationend)selfr   r   r   frame0	__class__s        `/var/www/it7/html/youtubeDownloader/venv/lib/python3.12/site-packages/moviepy/audio/AudioClip.pyr   zAudioClip.__init__D   sp    ?DH%"0D^^A&Fvz*!$T&\!2!"$DMDH      c              #     K   || j                   }t        j                  |      }|t        ||z        }t        || j                  z        }||z  dz   }t        j                  d||dz   dt              }	|j                  t        t        |                  D ]T  }
|	|
dz      |	|
   z
  }||k  sJ d|z  t        j                  |	|
   |	|
dz            z  }| j                  |||||       V yw)	zAIterator that returns the whole sound array of the clip by chunksNr   r   T)endpointdtype)chunk      ?)nbytesquantizer   
buffersize)r   proglogdefault_bar_loggerintr   nplinspaceiter_barr   rangearangeto_soundarray)r   	chunksizechunk_durationr   r%   r$   logger
total_sizenchunks	positionsisizetimingss                r   iter_chunkszAudioClip.iter_chunksU   s	     ;((C++F3%NS01It}},-
	)A-KK:w{TQTU	tE'N';< 	AQU#il2D9$$$SyBIIilIa!e<L$MMG$$sy %  		s   C1C3c           
      
   ||| j                   }d|z  |z  }| j                  |kD  rS| j                  dk(  rt        j                  nt        j
                  } |t        | j                  ||d|                  S t        j                  d| j                  d|z        }	 | j                  |      }|rPt        j                  dt        j                  d|            }dd	d
d|   }	dd|z  dz
  z  |z  j                  |	      }|S )a  
        Transforms the sound into an array that can be played by pygame
        or written in a wav file. See ``AudioClip.preview``.

        Parameters
        ----------

        fps
          Frame rate of the sound for the conversion.
          44100 for top quality.

        nbytes
          Number of bytes to encode the sound: 1 for 8bit sound,
          2 for 16bit, 4 for 32bit sound.

        r      )r   r%   r$   r0   r   r#   gGzgGz?int8int16int32)r   r;         )r   r   r   r*   vstackhstacktupler9   r.   r   maximumminimumastype)
r   ttr   r%   r$   r&   max_durationstacker	snd_arrayinttypes
             r   r/   zAudioClip.to_soundarrayt   s   ( :{hhz>C/L}}|+'+~~':"))		(( #hqJ )   YYq$--s;	 NN2&	

5"**T9*EFI W9&AGq6zA~.:BB7KIr   c                    |xr | j                   dkD  }t        j                  | j                         }| j                  ||      D ]1  }t        j                  |t        |      j                  d            }3 |r|S |d   S )z-Returns the maximum volume level of the clip.r   )r0   r2   r   )axis)r   r*   zerosr9   rD   absmax)r   stereor0   r2   maxir"   s         r   
max_volumezAudioClip.max_volume   s|     .DNNQ. xx'%%	&%I 	<E::dCJNNN$:;D	< t*47*r   filenamec
                 >   |s| j                   sd}n| j                   }|Rt        j                  j                  t        j                  j	                  |            \  }
}	 t
        |dd    d   d   }t        | |||||||||	
      S # t        $ r t        d      w xY w)a+  Writes an audio file from the AudioClip.


        Parameters
        ----------

        filename
          Name of the output file, as a string or a path-like object.

        fps
          Frames per second. If not set, it will try default to self.fps if
          already set, otherwise it will default to 44100.

        nbytes
          Sample width (set to 2 for 16-bit sound, 4 for 32-bit sound)

        buffersize
          The sound is not generated all at once, but rather made by bunches
          of frames (chunks). ``buffersize`` is the size of such a chunk.
          Try varying it if you meet audio problems (but you shouldn't
          have to). Default to 2000

        codec
          Which audio codec should be used. If None provided, the codec is
          determined based on the extension of the filename. Choose
          'pcm_s16le' for 16-bit wav and 'pcm_s32le' for 32-bit wav.

        bitrate
          Audio bitrate, given as a string like '50k', '500k', '3000k'.
          Will determine the size and quality of the output file.
          Note that it mainly an indicative goal, the bitrate won't
          necessarily be the this in the output file.

        ffmpeg_params
          Any additional parameters you would like to pass, as a list
          of terms, like ['-option1', 'value1', '-option2', 'value2']

        write_logfile
          If true, produces a detailed logfile named filename + '.log'
          when writing the file

        logger
          Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.

        iD  Nr   codecr   zoMoviePy couldn't find the codec associated with the filename. Provide the 'codec' parameter in write_audiofile.)rV   bitratewrite_logfileffmpeg_paramsr2   )	r   ospathsplitextbasenamer	   KeyError
ValueErrorr   )r   rT   r   r$   r&   rV   rW   rY   rX   r2   nameexts               r   write_audiofilezAudioClip.write_audiofile   s    v 88hh=(()9)9()CDID#'AB09!< !''
 	
   4 s    B Bc                 &    t        | |||||       y)a  
        Preview an AudioClip using ffplay

        Parameters
        ----------

        fps
            Frame rate of the sound. 44100 gives top quality, but may cause
            problems if your computer is not fast enough and your clip is
            complicated. If the sound jumps during the preview, lower it
            (11025 is still fine, 5000 is tolerable).

        buffersize
            The sound is not generated all at once, but rather made by bunches
            of frames (chunks). ``buffersize`` is the size of such a chunk.
            Try varying it if you meet audio problems (but you shouldn't
            have to).

        nbytes:
            Number of bytes to encode the sound: 1 for 8bit sound, 2 for
            16bit, 4 for 32bit sound. 2 bytes is fine.

        audio_flag, video_flag:
            Instances of class threading events that are used to synchronize
            video and audio during ``VideoClip.preview()``.
        )clipr   r&   r$   
audio_flag
video_flagNr   )r   r   r&   r$   re   rf   s         r   audiopreviewzAudioClip.audiopreview  s    < 	!!!	
r   c                 d    t        |t              rt        | |g      S t        t        |   |      S N)
isinstancer   concatenate_audioclipsr   __add__)r   otherr   s     r   rl   zAudioClip.__add__6  s.    eY')4-88Y-e44r   )NNN)NNNFr;   N)NNFr;   P  )Frn   N)Nr;     NNNFbar)Nro   r;   NN)__name__
__module____qualname____doc__r   r   r9   r/   rS   r   rb   rg   rl   __classcell__r   s   @r   r   r      s    -^ "   < FK2 2h+ J' U
 ( U
n OS$
 $
L5 5r   r   c                       e Zd ZdZd Zy)AudioArrayClipa  

    An audio clip made from a sound array.

    Parameters
    ----------

    array
      A Numpy array representing the sound, of size Nx1 for mono,
      Nx2 for stereo.

    fps
      Frames per second : speed at which the sound is supposed to be
      played.

    c                      t        j                          | _        | _        dt	        |      z  |z   _         fd}| _        t	        t         j                  d                   _	        y )Nr#   c                    t        | t        j                        rt        j                  j                  | z        j                  t              }|dk\  |t        j                        k  z  }t        j                  t        |       df      }j                  ||      ||<   |S t        j                  | z        }|dk  s|t        j                        k\  rdj                  d   z  S j                  |   S )zoComplicated, but must be able to handle the case where t
            is a list of the form sin(t).
            r   r;   )
rj   r*   ndarrayroundr   rF   r)   r   arrayrN   )t
array_indsin_arrayresultr6   r   s        r   r   z/AudioArrayClip.__init__.<locals>.frame_functionT  s     !RZZ(XXdhhl3::3?
&!O
S_0LM3q61+.#'::j.B#Cx 1%q5ATZZ0tzz!},,::a=(r   r   )
r   r   r}   r   r   r   r   r   r   r   )r   r}   r   r   s   `   r   r   zAudioArrayClip.__init__N  s[    d
c%j(3.	)" -T$.."345r   N)rq   rr   rs   rt   r    r   r   rx   rx   <  s    "6r   rx   c                   H     e Zd ZdZ fdZed        Zed        Zd Z xZ	S )CompositeAudioClipa  Clip made by composing several AudioClips.

    An audio clip made by putting together several audio clips.

    Parameters
    ----------

    clips
      List of audio clips, which may start playing at different times or
      together, depends on their ``start`` attributes. If all have their
      ``duration`` attribute set, the duration of the composite clip is
      computed automatically.
    c                    || _         t        d | j                   D              | _        d }| j                  D ]  }| nt        ||xs d      } d }| j                   D ]N  }t	        |d      st        |j                  t        j                        s5t        |j                  |xs d      }P t        | )  ||       y )Nc              3   4   K   | ]  }|j                     y wri   )r   .0rd   s     r   	<genexpr>z.CompositeAudioClip.__init__.<locals>.<genexpr>z  s     CT^^C   r   r   )r   r   )clipsrP   r   endsr   rj   r   numbersNumberr   r   )r   r   r   r   r   rd   r   s         r   r   zCompositeAudioClip.__init__x  s    
C

CC 99 	/C{3A.H	/ JJ 	.DtU#
488W^^(L$((CH1-	. 	(4r   c                 (    d | j                   D        S )z8Returns starting times for all clips in the composition.c              3   4   K   | ]  }|j                     y wri   )startr   s     r   r   z,CompositeAudioClip.starts.<locals>.<genexpr>  s     2t

2r   r   r   s    r   startszCompositeAudioClip.starts  s     3tzz22r   c                 (    d | j                   D        S )z6Returns ending times for all clips in the composition.c              3   4   K   | ]  }|j                     y wri   )r   r   s     r   r   z*CompositeAudioClip.ends.<locals>.<genexpr>  s     0T0r   r   r   s    r   r   zCompositeAudioClip.ends  s     1TZZ00r   c                    | j                   D cg c]  }|j                  |       }}t        | j                   |      D cg c]H  \  }}|dur?|j                  ||j                  z
        t        j                  |g      j                  z  J }}}t        |t
        j                        r+t        j                  t        |      | j                  f      }nt        j                  | j                        }|t        |      z   S c c}w c c}}w )z7Renders a frame for the composition for the time ``t``.F)r   
is_playingzipr   r   r*   r}   Trj   r{   rN   r   r   sum)r   r~   rd   played_partspartsoundszeros          r   r   z!CompositeAudioClip.frame_function  s    7;zzBt*BB "$**l;
dE! NN1tzz>*RXXtf-=-?-??
 
 a$88SVT^^45D88DNN+Dc&k!! C
s   DAD	)
rq   rr   rs   rt   r   propertyr   r   r   ru   rv   s   @r   r   r   i  s:    5& 3 3 1 1"r   r   c                    t        j                  dg| D cg c]  }|j                   c}      }t        | |dd       D cg c]  \  }}|j	                  |       }}}t        |      j                  |d         S c c}w c c}}w )zConcatenates one AudioClip after another, in the order that are passed
    to ``clips`` parameter.

    Parameters
    ----------

    clips
      List of audio clips, which will be played one after other.
    r   N)r*   cumsumr   r   
with_startr   with_duration)r   rd   
starts_endr~   newclipss        r   rk   rk     sy     AB5 A4 ABCJ25eZ_2MNwtQ"NHNh'55jnEE !BNs   A>
B)rt   r   rZ   numpyr*   r'   #moviepy.audio.io.ffmpeg_audiowriterr   &moviepy.audio.io.ffplay_audiopreviewerr   moviepy.Clipr   moviepy.decoratorsr   r   moviepy.toolsr	   r   rx   r   rk   r   r   r   <module>r      sV     	   A F  H )e5 e5P	*6Y *6Z;" ;"|Fr   