您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)怎么在python中利用多線程下載m3u8格式視頻,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
import datetime import os import re import threading import requests from queue import Queue # 預(yù)下載,獲取m3u8文件,讀出ts鏈接,并寫入文檔 def down(): # m3u8鏈接 url = 'https://ali-video.acfun.cn/mediacloud/acfun/acfun_video/segment/3zf_GAW6nFMuDXrTLL89OZYOZ4mwxGoASH6UcZbsj1_6eAxUxtp3xm8wFmGMNOnZ.m3u8?auth_key=1573739375-474267152-0-a5aa2b6df4cb4168381bf8b04d88ddb1' # 當(dāng)ts文件鏈接不完整時,需拼湊 # 大部分網(wǎng)站可使用該方法拼接,部分特殊網(wǎng)站需單獨拼接 base_url = re.split(r"[a-zA-Z0-9-_\.]+\.m3u8", url)[0] # print(base_url) resp = requests.get(url) m3u8_text = resp.text # print(m3u8_text) # 按行拆分m3u8文檔 ts_queue = Queue(10000) lines = m3u8_text.split('\n') # 找到文檔中含有ts字段的行 concatfile = 'cache/' + "s" + '.txt' for line in lines: if '.ts' in line: if 'http' in line: # print("ts>>", line) ts_queue.put(line) else: line = base_url + line ts_queue.put(line) # print('ts>>',line) filename = re.search('([a-zA-Z0-9-]+.ts)', line).group(1).strip() # 一定要先寫文件,因為線程的下載是無序的,文件無法按照 # 123456。。。去順序排序,而文件中的命名也無法保證是按順序的 # 這會導(dǎo)致下載的ts文件無序,合并時,就會順序錯誤,導(dǎo)致視頻有問題。 open(concatfile, 'a+').write("file %s\n" % filename) return ts_queue,concatfile # 線程模式,執(zhí)行線程下載 def run(ts_queue): tt_name = threading.current_thread().getName() while not ts_queue.empty(): url = ts_queue.get() r = requests.get(url, stream=True) filename = re.search('([a-zA-Z0-9-]+.ts)', url).group(1).strip() with open('cache/' + filename, 'wb') as fp: for chunk in r.iter_content(5242): if chunk: fp.write(chunk) print(tt_name + " " + filename + ' 下載成功') # 視頻合并方法,使用ffmpeg def merge(concatfile, name): try: path = 'cache/' + name + '.mp4' command = 'ffmpeg -y -f concat -i %s -crf 18 -ar 48000 -vcodec libx264 -c:a aac -r 25 -g 25 -keyint_min 25 -strict -2 %s' % (concatfile, path) os.system(command) print('視頻合并完成') except: print('合并失敗') if __name__ == '__main__': name = input('請輸入視頻名稱:') start = datetime.datetime.now().replace(microsecond=0) s,concatfile = down() # print(s,concatfile) threads = [] for i in range(15): t = threading.Thread(target=run, name='th-'+str(i), kwargs={'ts_queue': s}) threads.append(t) for t in threads: t.start() for t in threads: t.join() end = datetime.datetime.now().replace(microsecond=0) print('下載耗時:' + str(end - start)) merge(concatfile,name) over = datetime.datetime.now().replace(microsecond=0) print('合并耗時:' + str(over - end))
效果圖:
代碼開始:自己輸入視頻名稱(也可以去原網(wǎng)站爬名稱)
查看下載耗時,fmmpeg開始合并:
合并耗時:
關(guān)于怎么在python中利用多線程下載m3u8格式視頻就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。