o
    zi                     @   sr  d Z ddl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Z	ddl
mZ ddlmZ ddlmZ e	ed Ze	ed	 Zd
Zdd ZG dd dZedkrddlmZ eddddZejddddZejddddZejdddddZed ejdddddZe d d!Z!e!"e e!"e e!"e e!"e W d   dS 1 sw   Y  dS dS )"z
These are utilities that allow one to embed an AudioSignal
as a playable object in a Jupyter notebook, or to play audio from
the terminal, etc.
    N)NamedTemporaryFile   )	templates)_close_temp_files)format_figurezheaders.htmlzwidget.html.wavc                  C   s<   zdd l } W n   d} Y z	dd l}W | |fS    td)Nr   Fz8IPython must be installed in order to use this function!)ffmpyIPythonImportError)r   r	    r   L/home/ubuntu/.local/lib/python3.10/site-packages/audiotools/core/playback.py_check_imports   s   
r   c                   @   sb   e Zd ZddededefddZ					
			ddededededededefddZdd ZdS )	PlayMixinNTFextdisplayreturn_htmlc                 C   s
  |du rt }|dsd| n|}t \}}| j}g }t|Q tdddd}|| | |j |dkrW|rWtd|dd}	|| |j	|jdi|	jdid}
|

  n|}	|jj|	j|d	}|rj|j| W d   n1 stw   Y  |rd
|  d}|S )a  Embeds audio as a playable audio embed in a notebook, or HTML
        document, etc.

        Parameters
        ----------
        ext : str, optional
            Extension to use when saving the audio, by default ".wav"
        display : bool, optional
            This controls whether or not to display the audio when called. This
            is used when the embed is the last line in a Jupyter cell, to prevent
            the audio from being embedded twice, by default True
        return_html : bool, optional
            Whether to return the data wrapped in an HTML audio element, by default False

        Returns
        -------
        str
            Either the element for display, or the HTML string of it.
        N.zw+r   F)modesuffixdeletezK-write_xing 0 -codec:a libmp3lame -b:a 128k -y -hide_banner -loglevel error)inputsoutputs)dataratez<audio   controls   src='z'> </audio> )DEFAULT_EXTENSION
startswithr   sample_rater   r   appendwritenameFFmpegrunr   Audiosrc_attr)selfr   r   r   r   r	   srtmpfilestmp_wavtmp_convertedffaudio_elementr   r   r   embed'   s>   




zPlayMixin.embedr   100%10pxspecshowtitleadd_headersplayer_widthmarginplot_fnc                    s  ddl m   fdd}	t \}
}d}|r/tdt|}|dt|}|j|j| t}t	|tr?t
| |}||d< |di |   }| |j }|	 }|   td	 |	 }dd
d tdD }| j|dd}|d| }|d|}|d|}|d|}|dt|d  d}|dt|d  d}|j|j| |r|r|nd}||7 }|S dS )aE  Creates a playable widget with spectrogram. Inspired (heavily) by
        https://sjvasquez.github.io/blog/melnet/.

        Parameters
        ----------
        title : str, optional
            Title of plot, placed in upper right of top-most axis.
        ext : str, optional
            Extension for embedding, by default ".mp3"
        add_headers : bool, optional
            Whether or not to add headers (use for first embed, False for later embeds), by default True
        player_width : str, optional
            Width of the player, as a string in a CSS rule, by default "100%"
        margin : str, optional
            Margin on all sides of player, by default "10px"
        plot_fn : function, optional
            Plotting function to use (by default self.specshow).
        return_html : bool, optional
            Whether to return the data wrapped in an HTML audio element, by default False
        kwargs : dict, optional
            Keyword arguments to plot_fn (by default self.specshow).

        Returns
        -------
        HTML
            HTML object.
        r   Nc                     sL   t  }  j| ddd    | d t|  d}d	|}|S )Ntightr   )bbox_inches
pad_inchesasciizdata:image/png;base64,{0})
ioBytesIOsavefigcloseseekbase64	b64encodereaddecodeformat)bufferdata_uritagpltr   r   _save_fig_to_tag   s   

z*PlayMixin.widget.<locals>._save_fig_to_tag PLAYER_WIDTHMARGINr/   )   g      ?c                 s   s    | ]	}t tjV  qd S )N)randomchoicestringascii_uppercase).0_r   r   r   	<genexpr>   s    z#PlayMixin.widget.<locals>.<genexpr>
   F)r   r   	AUDIO_SRC	IMAGE_SRC
LEVELS_SRC	PLAYER_IDPADDING_AMOUNTr   px	MAX_WIDTHr   )matplotlib.pyplotpyplotr   headersreplacestrr   HTMLwidget
isinstancegetattrgcfget_size_inchesdpir.   r   joinranger+   r#   int)r$   r/   r   r0   r1   r2   r3   r   kwargsrG   rQ   r	   header_htmlwidget_htmlfigpixelsrD   
levels_tag	player_id
audio_elemhtmlr   rE   r   ra   `   sB   &


zPlayMixin.widgetc              
   C   sv   g }t |+ tddd}|| | |j t|  tdddddd	|jg W d
   | S 1 s4w   Y  | S )z
        Plays an audio signal if ffplay from the ffmpeg suite of tools is installed.
        Otherwise, will fail. The audio signal is written to a temporary file
        and then played with ffplay.
        r   F)r   r   ffplayz-nodispz	-autoexitz-hide_bannerz	-loglevelerrorN)r   r   r   r   r   print
subprocesscall)r$   r&   r'   r   r   r   play   s(   


zPlayMixin.play)NTF)Nr   Tr,   r-   r.   F)__name__
__module____qualname__r_   boolr+   ra   rx   r   r   r   r   r   &   s2    ;
`r   __main__)AudioSignalz(tests/audio/spk/f10_script4_produced.mp3   )offsetdurationWaveformwaveplotT)r3   r   SpectrogramF)r   r0   zWaveform + spectrogramwavespec)r3   r   r0   i@  zLowpassed audioz/tmp/index.htmlw)#__doc__r=   r8   rL   rN   rv   tempfiler   importlib_resourcespkg_resourcesrH   r   utilr   r   filesjoinpath	read_textr]   ra   r   r   r   ry   
audiotoolsr~   signal	wave_html	spec_htmlcombined_htmllow_passlowpass_htmlopenfr   r   r   r   r   <module>   s`     5



"