提取視頻中的音頻 Python只需要三行代碼!
身處數據爆炸增長的信息時代,各種各樣的數據都飛速增長,視頻數據也不例外。我們可以使用 python 來提取視頻中的音頻,而這僅僅需要安裝一個體量很小的 python 庫,然后執行三行代碼!
語音數據在數據分析領域極為重要。比如可以分析語義、口音、根據人的情緒等等。可以應用于偏好分析、謊話檢測等等。
一、提取音頻需要用到 python 的 moviepy 庫
moviepy的 github 地址:https://github.com/Zulko/moviepy
命令行 pip 安裝上 moviepy 即可!
pip install moviepy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
提取音頻:假設有一個 mp4 文件路徑為'D:pythonpycharm2020my_programvideo_processtest_01.mp4',我們想提取其中的音頻保存到'D:pythonpycharm2020my_programvideo_processvst01.mp3',三行 Python 代碼實現如下:
import moviepy.editor as mpy# 截取背景音樂audio_background = mpy.AudioFileClip(r’D:pythonpycharm2020my_programvideo_processtest_01.mp4’).subclip(1, 60)audio_background.write_audiofile(r’D:pythonpycharm2020my_programvideo_processvst01.mp3’)
結果如下:
執行上面的三行代碼,就會發現音頻文件已經成功提取到指定文件夾啦~ ~這里的視頻格式和音頻格式都支持其他格式,比如讀取 mp4 格式視頻,抽取其中的背景音樂保存為 MP3 格式音頻。
二、引力波繪制數據來源:
http://python123.io/dv/grawave.html http://python123.io/dv/H1_Strain.wav http://python123.io/dv/L1_Strain.wav http://python123.io/dv/wf_template.txt從配置文檔中讀取時間相關數據
import numpy as np # 科學計算所用的numpy庫import matplotlib.pyplot as plt # 繪圖所用的庫matplotlibfrom scipy.io import wavfile # 讀取波形文件所用的庫rate_h, hstrain = wavfile.read(r'H1_Strain.wav', 'rb') # 讀取音頻文件rate_l, lstrain = wavfile.read(r'L1_Strain.wav', 'rb')# reftime, ref_H1 = np.genfromtxt(’GW150914_4_NR_waveform_template.txt’).transpose()reftime, ref_H1 = np.genfromtxt(’wf_template.txt’).transpose() # 使用python123.io下載txt文件
構造應變數據
htime_interval = 1 / rate_hltime_interval = 1 / rate_lfig = plt.figure(figsize=(12, 6)) # 創建大小為12*6的繪圖空間# 丟失信號起始點htime_len = hstrain.shape[0] / rate_h # 讀取數據第一維的長度,得到函數在坐標軸上總長度htime = np.arange(-htime_len / 2, htime_len / 2, htime_interval) # (起點,終點,時間間隔)
使用來自 “H1” 探測器的數據作圖
plth = fig.add_subplot(221) # 設置繪圖區域plth.plot(htime, hstrain, ’r’) # 畫出以時間為x軸,應變數據為y軸的圖像,‘y’為黃色plth.set_xlabel(’Time (seconds)’)plth.set_ylabel(’H1 Strain’)plth.set_title(’H1 Strain’)
繪制 L1 Strain 和Template
ltime_len = lstrain.shape[0] / rate_lltime = np.arange(-ltime_len / 2, ltime_len / 2, ltime_interval)pltl = fig.add_subplot(222)pltl.plot(ltime, lstrain, ’k’)pltl.set_xlabel(’Time (seconds)’)pltl.set_ylabel(’L1 Strain’)pltl.set_title(’L1 Strain’)pltref = fig.add_subplot(212)pltref.plot(reftime, ref_H1, ’purple’)pltref.set_xlabel(’Time (seconds)’)pltref.set_ylabel(’Template Strain’)pltref.set_title(’Template’)fig.tight_layout() # 自動調整圖像外部邊緣
保存并顯示圖像
plt.savefig('Gravitational_Waves_Original.png') # 保存圖像為png格式plt.show()plt.close(fig)
結果如下:
以上就是提取視頻中的音頻 Python只需要三行代碼!的詳細內容,更多關于python 提取視頻中的音頻的資料請關注好吧啦網其它相關文章!
相關文章: