{"id":17675599,"url":"https://github.com/ernanej/audio-spectrum-visualizer","last_synced_at":"2025-03-30T17:14:47.996Z","repository":{"id":237413281,"uuid":"631764415","full_name":"ErnaneJ/audio-spectrum-visualizer","owner":"ErnaneJ","description":"Visualization of the spectral content of an audio file using python.","archived":false,"fork":false,"pushed_at":"2023-04-24T02:21:41.000Z","size":2368,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-05T18:59:54.212Z","etag":null,"topics":["audio-processing","pds","python","spectrum-analyzer"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ErnaneJ.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-04-24T02:15:45.000Z","updated_at":"2023-04-24T02:21:46.000Z","dependencies_parsed_at":"2024-05-01T14:30:12.740Z","dependency_job_id":"e56f6eb6-d737-456e-b1cd-8fe7fcfe7182","html_url":"https://github.com/ErnaneJ/audio-spectrum-visualizer","commit_stats":null,"previous_names":["ernanej/audio-spectrum-visualizer"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ErnaneJ%2Faudio-spectrum-visualizer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ErnaneJ%2Faudio-spectrum-visualizer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ErnaneJ%2Faudio-spectrum-visualizer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ErnaneJ%2Faudio-spectrum-visualizer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ErnaneJ","download_url":"https://codeload.github.com/ErnaneJ/audio-spectrum-visualizer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246351017,"owners_count":20763232,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["audio-processing","pds","python","spectrum-analyzer"],"created_at":"2024-10-24T07:22:51.239Z","updated_at":"2025-03-30T17:14:47.962Z","avatar_url":"https://github.com/ErnaneJ.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Visualização do conteúdo espectral de um arquivo de áudio\n\nO script análisado abaixo pode ser executado utilizando o arquivo **spectrum_welch.py** juntamente com o áudio **581010__xcreenplay__smoking-in-the-angel-section2.wav** presente na pasta assets.\n\nPrimeiramente importamos as bibliotecas necessárias.\n\n```py\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy.io import wavfile\nfrom scipy.signal import welch\nfrom scipy import fftpack\n```\n\nApós importarmos as bibliotecas que serão utilizadas, carregamos o arquivo de áudio.\n\n```py\n# Load audio file\nsamplerate, data = wavfile.read('./assets/581010__xcreenplay__smoking-in-the-angel-section2.wav')\n\n# Loads the file in two channels (stereo audio)\nprint(f\"number of channels = {data.shape[1]}\") # =\u003e number of channels = 2\n\n# Total time = number of samples / fs\nlength = data.shape[0] / samplerate\nprint(f\"duration = {length}s\") # =\u003e duration = 14.76922902494331s\n```\nA seguir, plotamos as figuras no domínio do tempo.\n\n```py\n# Plot the figures over time\n# Interpolate to determine time axis\ntime = np.linspace(0., length, data.shape[0])\n\n# Plots the left and right channels\nplt.figure(1)\nplt.plot(time, data[:, 0], label=\"Left channel\")\nplt.legend()\nplt.xlabel(\"Time [s]\")\nplt.ylabel(\"Amplitude\")\nplt.show()\n\nplt.figure(2)\nplt.plot(time, data[:, 1], label=\"Right channel\")\nplt.legend()\nplt.xlabel(\"Time [s]\")\nplt.ylabel(\"Amplitude\")\nplt.show()\n```\n\n| Left channel | Right channel |\n|:-------------:|:-------------:|\n![](./assets/spectrum_welch_left_channel_audio.png) | ![](./assets/spectrum_welch_right_channel_audio.png)|\n|||\n\nPara plotar o conteúdo espectral, utilizaremos a função [*welch*](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.welch.html).\n\n```py\n# Estimates the signal spectrum using the welch function\nx  = data[:, 0] # =\u003e left channel\nfs = 2*np.pi\n# fs = samplerate\nf, Pxx_spec = welch(x, fs, 'flattop', 512, scaling='spectrum')\n```\n\nA seguir, podemos vizualizar o conteúdo espectral do sinal no intervalo $0$ e $\\pi$.\n\n```py\n# Plots the signal spectrum for normalized frequencies between 0 1 pi (positive frequencies)\n\nplt.figure(3)\nplt.semilogy(f, Pxx_spec)\nplt.xlabel('Frequency [rad]')\nplt.ylabel('Spectrum')\nplt.show()\n```\n\n\u003cp align='center'\u003e\n  \u003cimg src=\"./assets/signal_spectrum_for_normalized_frequencies_between_0_and_1_pi.png\"/\u003e\n\u003c/p\u003e\n\n**Exemplo de modulação:**\n\n```py\n# Frequency of the generated cosine function\nf_c = 10000 #10KHz\nT = 1/f_c\n\n# Number of input file samples\nns = data.shape[0]\n\n# Initializing arrays to collect 1s of data\ncosseno  = [0]*ns\nt_axis = np.arange(0., ns)*T\n\n# Cosine function that will be used in the modulation\nfor i in range(ns):\n    cosseno[i] = np.cos(2 * np.pi * f_c * i * T) \n\n#Estimates the signal spectrum using the welch function\nx  = data[:, 0]*cosseno # =\u003e left channel\nfs = 2*np.pi\nf, Pxx_spec = welch(x, fs, 'flattop', 512, scaling='spectrum')\n\nplt.figure(4)\nplt.plot(f, Pxx_spec)\nplt.xlabel('Frequency [Hz]')\nplt.ylabel('Spectrum')\nplt.show()\n```\n\n\u003cp align='center'\u003e\n  \u003cimg src=\"./assets/example_of_modulation.png\"/\u003e\n\u003c/p\u003e\n\n## Plota espectro utilizando função FFT\n\nNão utilizamos, nesse momento, a transformada rápida de Fourier (FFT, do inglês Fast Fourier Transform). Porém, abaixo está um exemplo de como realizar a mostragem do spectrum utilizanddo FFT.\n\n```py\n# Plot spectrum using FFT function\nnfft=4096\nfreq = np.linspace(0., samplerate, nfft) # Interpolate to determine frequency axis\nsig_fft = fftpack.fft(x,nfft)\nplt.figure(4)\nplt.plot(freq, np.abs(sig_fft))\nplt.xlabel('Frequency [Hz]')\nplt.ylabel('Amplitude spectrum')\nplt.show()\n```\n\n\u003cp align='center'\u003e\n  \u003cimg src=\"./assets/plot_spectrum_using_fft_function.png\"/\u003e\n\u003c/p\u003e\n\n## Informações Adicionais\n\n### Processamento digital de sinais (PDS) em python\n\nO livro Think DSP trata de forma didática o processamento digital de sinais, usando exemplos de implementação em Python. O livro pode ser baixado ou visualizado online no site:\n\n* [greenteapress.com](https://greenteapress.com/wp/think-dsp/)\n\nO livro Think DSP faz uso da biblioteca *SciPy*, que contém um conjunto de funções\nlargamente utilizadas em PDS. Pode-se consultar as funções pertencentes a esta biblioteca em:\n\n* [docs.scipy.org](https://docs.scipy.org/doc/scipy/reference/signal.html)\n\n---\n\nOutras fontes de consulta para aplicações de PDS podem ser os cursos disponibilizados na plataforma Coursera, em:\n\n* [coursera.org - dsp1#syllabus](https://www.coursera.org/learn/dsp1#syllabus)\n* [coursera.org - dsp2#reviews](https://www.coursera.org/learn/dsp2#reviews)\n\n### Banco de dados de sinais de áudio\n\nUma das aplicações mais clássicas de PDS é o processamento de sinais digitais de áudio. Para se testar algoritmos de PDS, é possível encontrar diversos arquivos de áudio em formato digital no site:\n\n* [freesound](https://freesound.org/browse/)\n\nPara baixar algum destes sinais, deve-se criar um usuário no site, o que pode ser feito de forma bem simples.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fernanej%2Faudio-spectrum-visualizer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fernanej%2Faudio-spectrum-visualizer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fernanej%2Faudio-spectrum-visualizer/lists"}