├── Config.json
├── Danmu.py
├── LICENSE
├── Push.py
├── README.md
├── fonts
└── msyh.ttc
├── log
└── Downloads.log
├── resource
├── img
│ ├── 001.jpg
│ ├── 002.jpg
│ ├── 003.jpg
│ ├── 004.jpg
│ ├── 005.jpg
│ ├── 006.jpg
│ ├── 007.jpg
│ ├── 008.jpg
│ ├── 009.jpg
│ ├── 010.jpg
│ ├── 011.jpg
│ ├── 012.jpg
│ ├── 013.jpg
│ ├── 014.jpg
│ ├── 015.jpg
│ ├── 016.jpg
│ ├── 017.jpg
│ └── 018.jpg
├── music
│ ├── Kyle Xian - 永遠のひとつ(动画《ISLAND》OP)(Cover 田村ゆかり).mp3
│ ├── default.ass
│ └── 堀江晶太 - Sincerely (off vocal).mp3
├── night
│ └── default.ass
├── playlist
│ └── empty_file
└── users
│ └── not_empty
├── restart.sh
├── service
├── AssMaker.py
├── GetInfo.py
└── PostDanmu.py
├── start.sh
├── stop.sh
└── tools
├── php
├── NeteaseMusicAPI_mini.php
└── index.php
└── video_convert_tool.py
/Config.json:
--------------------------------------------------------------------------------
1 | {
2 | "path": "/root/Server-Music-Live-On-Bilibili",
3 | "musicapi": "https://api.yuncaioo.com/bililive/",
4 | "freespace": "15360",
5 | "gift": "0",
6 | "rtmp": {
7 | "url": "",
8 | "code": "",
9 | "bitrate": "192"
10 | },
11 | "danmu": {
12 | "cookie": "",
13 | "token": "",
14 | "roomid": "4059464",
15 | "size": "20"
16 | },
17 | "nightvideo": {
18 | "use": "1"
19 | }
20 | }
--------------------------------------------------------------------------------
/Danmu.py:
--------------------------------------------------------------------------------
1 | #coding:utf-8
2 | import asyncio
3 | import aiohttp
4 | import xml.dom.minidom
5 | import random
6 | import json
7 | from struct import *
8 | import json
9 | import re
10 | #import Config
11 | import numpy
12 | import os
13 | import service.PostDanmu
14 | import urllib
15 | import urllib.request
16 | import json
17 |
18 | config = json.load(open('./Config.json', encoding='utf-8'))
19 |
20 | TURN_WELCOME = 1
21 | TURN_GIFT = 1
22 |
23 | class bilibiliClient():
24 | def __init__(self):
25 | self._CIDInfoUrl = 'http://live.bilibili.com/api/player?id=cid:'
26 | self._roomId = 0
27 | self._ChatPort = 788
28 | self._protocolversion = 1
29 | self._reader = 0
30 | self._writer = 0
31 | self.connected = False
32 | self._UserCount = 0
33 | self._ChatHost = 'livecmt-1.bilibili.com'
34 |
35 | #self._roomId = input('请输入房间号:')
36 | self._roomId = int(config['danmu']['roomid'])
37 |
38 | async def connectServer(self):
39 | print ('正在进入房间')
40 | # with aiohttp.ClientSession() as s:
41 | # async with s.get('http://live.bilibili.com/' + str(self._roomId)) as r:
42 | # html = await r.text()
43 | # m = re.findall(r'ROOMID\s=\s(\d+)', html)
44 | # ROOMID = m[0]
45 | # self._roomId = int(ROOMID)
46 | # async with s.get(self._CIDInfoUrl + ROOMID) as r:
47 | # xml_string = '' + await r.text() + ''
48 | # dom = xml.dom.minidom.parseString(xml_string)
49 | # root = dom.documentElement
50 | # server = root.getElementsByTagName('server')
51 | # self._ChatHost = server[0].firstChild.data
52 |
53 |
54 |
55 | reader, writer = await asyncio.open_connection(self._ChatHost, self._ChatPort)
56 | self._reader = reader
57 | self._writer = writer
58 | print ('链接弹幕中')
59 | if (await self.SendJoinChannel(self._roomId) == True):
60 | self.connected = True
61 | print ('进入房间成功')
62 | print ('链接弹幕成功')
63 | await self.ReceiveMessageLoop()
64 |
65 | async def HeartbeatLoop(self):
66 | while self.connected == False:
67 | await asyncio.sleep(0.5)
68 |
69 | while self.connected == True:
70 | await self.SendSocketData(0, 16, self._protocolversion, 2, 1, "")
71 | await asyncio.sleep(30)
72 |
73 |
74 | async def SendJoinChannel(self, channelId):
75 | self._uid = (int)(100000000000000.0 + 200000000000000.0*random.random())
76 | body = '{"roomid":%s,"uid":%s}' % (channelId, self._uid)
77 | await self.SendSocketData(0, 16, self._protocolversion, 7, 1, body)
78 | return True
79 |
80 |
81 | async def SendSocketData(self, packetlength, magic, ver, action, param, body):
82 | bytearr = body.encode('utf-8')
83 | if packetlength == 0:
84 | packetlength = len(bytearr) + 16
85 | sendbytes = pack('!IHHII', packetlength, magic, ver, action, param)
86 | if len(bytearr) != 0:
87 | sendbytes = sendbytes + bytearr
88 | self._writer.write(sendbytes)
89 | await self._writer.drain()
90 |
91 |
92 | async def ReceiveMessageLoop(self):
93 | while self.connected == True:
94 | tmp = await self._reader.read(4)
95 | expr, = unpack('!I', tmp)
96 | tmp = await self._reader.read(2)
97 | tmp = await self._reader.read(2)
98 | tmp = await self._reader.read(4)
99 | num, = unpack('!I', tmp)
100 | tmp = await self._reader.read(4)
101 | num2 = expr - 16
102 |
103 | if num2 != 0:
104 | num -= 1
105 | if num==0 or num==1 or num==2:
106 | tmp = await self._reader.read(4)
107 | num3, = unpack('!I', tmp)
108 | #print ('房间人数为 %s' % num3)
109 | self._UserCount = num3
110 | continue
111 | elif num==3 or num==4:
112 | tmp = await self._reader.read(num2)
113 | # strbytes, = unpack('!s', tmp)
114 | try: # 为什么还会出现 utf-8 decode error??????
115 | messages = tmp.decode('utf-8')
116 | except:
117 | continue
118 | self.parseDanMu(messages)
119 | continue
120 | elif num==5 or num==6 or num==7:
121 | tmp = await self._reader.read(num2)
122 | continue
123 | else:
124 | if num != 16:
125 | tmp = await self._reader.read(num2)
126 | else:
127 | continue
128 |
129 | def parseDanMu(self, messages):
130 | try:
131 | dic = json.loads(messages)
132 | except: # 有些情况会 jsondecode 失败,未细究,可能平台导致
133 | return
134 | cmd = dic['cmd']
135 | if cmd == 'LIVE':
136 | print ('直播开始')
137 | return
138 | if cmd == 'PREPARING':
139 | print ('房主准备中')
140 | return
141 | if cmd == 'DANMU_MSG':
142 | commentText = dic['info'][1]
143 | commentUser = dic['info'][2][1]
144 | # isAdmin = dic['info'][2][2] == '1'
145 | # isVIP = dic['info'][2][3] == '1'
146 | # if isAdmin:
147 | # commentUser = '管理员 ' + commentUser
148 | # if isVIP:
149 | # commentUser = 'VIP ' + commentUser
150 | try:
151 | print (commentUser + ' 说: ' + commentText)
152 | service.PostDanmu.pick_msg(commentText,commentUser)
153 | except:
154 | pass
155 | return
156 | if cmd == 'SEND_GIFT' and TURN_GIFT == 1:
157 | GiftName = dic['data']['giftName']
158 | GiftUser = dic['data']['uname']
159 | Giftrcost = dic['data']['rcost']
160 | GiftNum = dic['data']['num']
161 | try:
162 | print(GiftUser + ' 送出了 ' + str(GiftNum) + ' 个 ' + GiftName)
163 | gift_count = 0
164 | try:
165 | gift_count = numpy.load('resource/users/'+GiftUser+'.npy')
166 | except:
167 | gift_count = 0
168 | try:
169 | os.remove('resource/users/'+GiftUser+'.npy')
170 | except:
171 | print('delete error')
172 | print('获取'+GiftUser+'送过'+str(gift_count)+'个瓜子')
173 | f = urllib.request.urlopen("https://api.live.bilibili.com/gift/v3/live/gift_config")
174 | gift_info = json.loads(f.read().decode('utf-8'))
175 | for i in gift_info['data']:
176 | if i['name'] == GiftName:
177 | gift_count = gift_count + GiftNum * i['price']
178 | print('[log]gift match',i['name'],i['price'])
179 | print(GiftUser+'瓜子数改为'+str(gift_count))
180 | try:
181 | numpy.save('resource/users/'+GiftUser+'.npy', gift_count)
182 | except:
183 | print('create error')
184 | service.PostDanmu.send_dm_long('感谢'+GiftUser+'送的'+str(GiftNum)+'个'+GiftName+'!')
185 | except:
186 | pass
187 | return
188 | if cmd == 'WELCOME' and TURN_WELCOME == 1:
189 | commentUser = dic['data']['uname']
190 | try:
191 | print ('欢迎 ' + commentUser + ' 进入房间')
192 | service.PostDanmu.send_dm_long('欢迎' + commentUser + '进入直播间!')
193 | except:
194 | pass
195 | return
196 | return
197 |
198 |
199 | try:
200 | danmuji = bilibiliClient()
201 | tasks = [
202 | danmuji.connectServer() ,
203 | danmuji.HeartbeatLoop()
204 | ]
205 | loop = asyncio.get_event_loop()
206 | try:
207 | loop.run_until_complete(asyncio.wait(tasks))
208 | except KeyboardInterrupt:
209 | danmuji.connected = False
210 | for task in asyncio.Task.all_tasks():
211 | task.cancel()
212 | loop.run_forever()
213 | loop.close()
214 | os.system("screen -dm python3 "+config['path']+"/Danmu.py")#自动重启
215 | except Exception as e: #防炸
216 | print('shit')
217 | print(e)
218 | os.system("screen -dm python3 "+config['path']+"/Danmu.py")#自动重启
219 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Push.py:
--------------------------------------------------------------------------------
1 | #coding:utf-8
2 | import os
3 | import sys
4 | import time
5 | import random
6 | from mutagen.mp3 import MP3
7 | import json
8 | #import Config
9 | import shutil
10 | import _thread
11 | import service.AssMaker
12 |
13 | config = json.load(open('./Config.json', encoding='utf-8'))
14 | path = config['path']
15 | rtmp = config['rtmp']['url']
16 | live_code = config['rtmp']['code']
17 | nightvideo = bool(int(config['nightvideo']['use']))
18 |
19 | #格式化时间,暂时没啥用,以后估计也没啥用
20 | def convert_time(n):
21 | s = n%60
22 | m = int(n/60)
23 | return '00:'+"%02d"%m+':'+"%02d"%s
24 |
25 | #移动放完的视频到缓存文件夹
26 | def remove_v(filename):
27 | try:
28 | #shutil.move(path+'/resource/playlist/'+filename,path+'/resource/music/')
29 | os.remove(path+'/resource/playlist/'+filename)
30 | except Exception as e:
31 | print(e)
32 | try:
33 | os.remove(path+'/resource/playlist/'+filename.replace(".flv",'')+'ok.ass')
34 | os.remove(path+'/resource/playlist/'+filename.replace(".flv",'')+'ok.info')
35 | except Exception as e:
36 | print(e)
37 | print('delete error')
38 |
39 | while True:
40 | try:
41 | if (time.localtime()[3] <= 5) and nightvideo: #time.localtime()[3] >= 23 or
42 | print('night is comming~') #晚上到咯~
43 | night_files = os.listdir(path+'/resource/night') #获取所有缓存文件
44 | night_files.sort() #排序文件
45 | night_ran = random.randint(0,len(night_files)-1) #随机抽一个文件
46 | # if(night_files[night_ran].find('.flv') != -1): #如果为flv视频
47 | # #直接暴力推流
48 | # print('ffmpeg -threads 1 -re -i "'+path+"/resource/night/"+night_files[night_ran]+'" -vcodec copy -acodec copy -f flv "'+rtmp+live_code+'"')
49 | # os.system('ffmpeg -threads 1 -re -i "'+path+"/resource/night/"+night_files[night_ran]+'" -vcodec copy -acodec copy -f flv "'+rtmp+live_code+'"')
50 | if(night_files[night_ran].find('.mp3') != -1): #如果为mp3
51 | pic_files = os.listdir(path+'/resource/img') #获取准备的图片文件夹中的所有图片
52 | pic_files.sort() #排序数组
53 | pic_ran = random.randint(0,len(pic_files)-1) #随机选一张图片
54 | audio = MP3(path+'/resource/night/'+night_files[night_ran]) #获取mp3文件信息
55 | seconds=audio.info.length #获取时长
56 | print('mp3 long:'+convert_time(seconds))
57 | if not os.path.isfile(path+'/resource/night/'+night_files[night_ran]+'.ass'):
58 | service.AssMaker.make_ass('../night/'+night_files[night_ran].replace('.mp3',''),'当前是晚间专属时间哦~时间范围:凌晨0-5点\\N大家晚安哦~做个好梦~\\N当前文件名:'+night_files[night_ran],path)
59 | print('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/night/'+night_files[night_ran]+'" -vf ass="'+path+'/resource/night/'+night_files[night_ran]+'.ass" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
60 | os.system('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/night/'+night_files[night_ran]+'" -vf ass="'+path+'/resource/night/'+night_files[night_ran].replace('.mp3','')+'.ass" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
61 | continue
62 |
63 | files = os.listdir(path+'/resource/playlist') #获取文件夹下全部文件
64 | files.sort() #排序文件,按文件名(点播时间)排序
65 | count=0 #总共匹配到的点播文件统计
66 | for f in files:
67 | if((f.find('.mp3') != -1) and (f.find('.download') == -1)): #如果是mp3文件
68 | print(path+'/resource/playlist/'+f)
69 | seconds = 600
70 | bitrate = 0
71 | try:
72 | audio = MP3(path+'/resource/playlist/'+f) #获取mp3文件信息
73 | seconds=audio.info.length #获取时长
74 | bitrate=audio.info.bitrate #获取码率
75 | print(audio.info.length)
76 | except Exception as e:
77 | print(e)
78 | bitrate = 99999999999
79 |
80 | print('mp3 long:'+convert_time(seconds))
81 | if((seconds > 600) | (bitrate > 400000)): #大于十分钟就不播放/码率限制400k以下
82 | print('too long/too big,delete')
83 | else:
84 | pic_files = os.listdir(path+'/resource/img') #获取准备的图片文件夹中的所有图片
85 | pic_files.sort() #排序数组
86 | pic_ran = random.randint(0,len(pic_files)-1) #随机选一张图片
87 | #推流
88 | print('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/playlist/'+f+'" -vf ass="'+path+"/resource/playlist/"+f.replace(".mp3",'')+'.ass'+'" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
89 | os.system('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/playlist/'+f+'" -vf ass="'+path+"/resource/playlist/"+f.replace(".mp3",'')+'.ass'+'" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
90 | try: #放完后删除mp3文件、删除字幕、删除点播信息
91 | shutil.move(path+'/resource/playlist/'+f,path+'/resource/music/')
92 | shutil.move(path+'/resource/playlist/'+f.replace(".mp3",'')+'.ass',path+'/resource/music/')
93 | #os.remove(path+'/resource/playlist/'+f)
94 | #os.remove(path+'/resource/playlist/'+f.replace(".mp3",'')+'.ass')
95 | except Exception as e:
96 | print(e)
97 | try:
98 | os.remove(path+'/resource/playlist/'+f.replace(".mp3",'')+'.info')
99 | os.remove(path+'/resource/playlist/'+f)
100 | os.remove(path+'/resource/playlist/'+f.replace(".mp3",'')+'.ass')
101 | except:
102 | print('delete error')
103 | count+=1 #点播统计加一
104 | break
105 | # if((f.find('ok.flv') != -1) and (f.find('.download') == -1) and (f.find('rendering') == -1)): #如果是有ok标记的mp4文件
106 | # print('flv:'+f)
107 | # #直接推流
108 | # print('ffmpeg -threads 1 -re -i "'+path+"/resource/playlist/"+f+'" -vcodec copy -acodec copy -f flv "'+rtmp+live_code+'"')
109 | # os.system('ffmpeg -threads 1 -re -i "'+path+"/resource/playlist/"+f+'" -vcodec copy -acodec copy -f flv "'+rtmp+live_code+'"')
110 | # os.rename(path+'/resource/playlist/'+f,path+'/resource/playlist/'+f.replace("ok","")) #修改文件名,以免下次循环再次匹配
111 | # _thread.start_new_thread(remove_v, (f.replace("ok",""),)) #异步搬走文件,以免推流卡顿
112 | # count+=1 #点播统计加一
113 | # break
114 | if(count == 0): #点播统计为0,说明点播的都放完了
115 | print('no media')
116 | mp3_files = os.listdir(path+'/resource/music') #获取所有缓存文件
117 | mp3_files.sort() #排序文件
118 | mp3_ran = random.randint(0,len(mp3_files)-1) #随机抽一个文件
119 |
120 | if(mp3_files[mp3_ran].find('.mp3') != -1): #如果是mp3文件
121 | pic_files = os.listdir(path+'/resource/img') #获取准备的图片文件夹中的所有图片
122 | pic_files.sort() #排序数组
123 | pic_ran = random.randint(0,len(pic_files)-1) #随机选一张图片
124 | audio = MP3(path+'/resource/music/'+mp3_files[mp3_ran]) #获取mp3文件信息
125 | seconds=audio.info.length #获取时长
126 | print('mp3 long:'+convert_time(seconds))
127 | #推流
128 | if(os.path.isfile(path+'/resource/music/'+mp3_files[mp3_ran].replace(".mp3",'')+'.ass')):
129 | print('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/music/'+mp3_files[mp3_ran]+'" -vf ass="'+path+"/resource/music/"+mp3_files[mp3_ran].replace(".mp3",'')+'.ass'+'" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
130 | os.system('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/music/'+mp3_files[mp3_ran]+'" -vf ass="'+path+"/resource/music/"+mp3_files[mp3_ran].replace(".mp3",'')+'.ass'+'" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
131 | else:
132 | print('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/music/'+mp3_files[mp3_ran]+'" -vf ass="'+path+'/resource/music/default.ass" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
133 | os.system('ffmpeg -threads 1 -re -loop 1 -r 15 -t '+str(int(seconds))+' -f image2 -i "'+path+'/resource/img/'+pic_files[pic_ran]+'" -i "'+path+'/resource/music/'+mp3_files[mp3_ran]+'" -vf ass="'+path+'/resource/music/default.ass" -x264-params "profile=high:level=5.1" -pix_fmt yuv420p -b '+config['rtmp']['bitrate']+'k -vcodec libx264 -acodec copy -f flv "'+rtmp+live_code+'"')
134 | # if(mp3_files[mp3_ran].find('.flv') != -1): #如果为flv视频
135 | # #直接推流
136 | # print('ffmpeg -threads 1 -re -i "'+path+"/resource/music/"+mp3_files[mp3_ran]+'" -vcodec copy -acodec copy -f flv "'+rtmp+live_code+'"')
137 | # os.system('ffmpeg -threads 1 -re -i "'+path+"/resource/music/"+mp3_files[mp3_ran]+'" -vcodec copy -acodec copy -f flv "'+rtmp+live_code+'"')
138 | except Exception as e:
139 | print(e)
140 |
141 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Server-Music-Live-On-Bilibili
2 |
3 | B站直播音乐点播台-服务器版
4 |
5 | 基于 [https://github.com/chenxuuu/24h-raspberry-live-on-bilibili](https://github.com/chenxuuu/24h-raspberry-live-on-bilibili) 二次开发
6 |
7 | Demo: [https://live.bilibili.com/4059464](https://live.bilibili.com/4059464)
8 |
9 | -------
10 |
11 | ### 此版本的功能
12 |
13 | - 弹幕点歌
14 | - 弹幕反馈(发送弹幕)
15 | - 自定义介绍字幕
16 | - 歌词滚动显示,同时滚动显示翻译歌词
17 | - 切歌
18 | - 显示排队播放歌曲
19 | - 闲时随机播放预留歌曲
20 | - 播放音乐时随机显示背景图片
21 | - 已点播歌曲自动进入缓存,无人点播时随机播放
22 | - 存储空间达到设定值时,自动按点播时间顺序删除音乐来释放空间
23 | - 实时显示歌曲长度
24 | - 根据投喂礼物的多少来决定是否允许点播
25 |
26 | ### 与原版的区别
27 |
28 | - 文件结构不同
29 | - 配置文件为 json
30 | - 不能使用弹幕点MV
31 | - 没有视频推流功能
32 | - 不能获取实时cpu温度
33 |
34 | ### 已知问题
35 |
36 | - 换歌、视频时会闪断
37 |
38 | -------
39 |
40 | ## 安装说明
41 |
42 | 此版本仅在 Ubuntu 16.04 测试通过,其它系统请自测
43 |
44 | ## 安装依赖
45 |
46 | ```Bash
47 | sudo apt-get update
48 | sudo apt-get -y install autoconf automake build-essential libass-dev libfreetype6-dev libtheora-dev libtool libvorbis-dev pkg-config texinfo wget zlib1g-dev
49 | ```
50 |
51 | libmp3lame:
52 | ```Bash
53 | sudo apt-get install -y libmp3lame-dev
54 | ```
55 |
56 | libopus:
57 | ```Bash
58 | sudo apt-get install -y libopus-dev
59 | ```
60 |
61 | libvpx:
62 | ```Bash
63 | sudo apt-get install -y libvpx-dev
64 | ```
65 |
66 | libomxil-bellagio:
67 | ```Bash
68 | sudo apt-get install -y libomxil-bellagio-dev
69 | ```
70 |
71 | ffmpeg、x264编码器:
72 | ```Bash
73 | sudo apt-get install -y ffmpeg
74 | ```
75 |
76 | x264、x265编码器:
77 | ```Bash
78 | sudo apt-get install -y x264 x265 libx264 libx265
79 | ```
80 |
81 | 安装python3:
82 |
83 | ```Bash
84 | sudo apt-get install -y python3
85 | ```
86 |
87 | 安装pip3:
88 | ```Bash
89 | sudo apt-get install -y python3-pip
90 | ```
91 |
92 | 安装python3的mutagen库:
93 | ```Bash
94 | sudo pip3 install mutagen
95 | ```
96 |
97 | 安装python3的moviepy库:
98 | ```Bash
99 | sudo pip3 install moviepy
100 | ```
101 |
102 | 安装python3的aiohttp库:
103 | ```Bash
104 | sudo pip3 install aiohttp
105 | ```
106 |
107 | 安装python3的numpy需要的库:
108 | ```Bash
109 | sudo apt-get install libatlas-base-dev
110 | ```
111 |
112 | 安装python3的requests库:
113 | ```Bash
114 | sudo pip3 install requests
115 | ```
116 |
117 | 安装screen:
118 | ```Bash
119 | sudo apt-get install -y screen
120 | ```
121 |
122 | 安装中文字体(此方法可能不适用你的服务器,如果无法安装请自行百度):
123 | ```Bash
124 | sudo apt install fontconfig
125 | sudo apt-get install ttf-mscorefonts-installer
126 | sudo apt-get install -y --force-yes --no-install-recommends fonts-wqy-microhei
127 | sudo apt-get install -y --force-yes --no-install-recommends ttf-wqy-zenhei
128 | #可能有装不上的,应该问题不大
129 |
130 | # 查看中文字体 --确认字体是否安装成功
131 | fc-list :lang=zh-cn
132 | ```
133 |
134 | (字体安装来自[ubuntu下 bilibili直播推流 ffmpeg rtmp推送](https://ppx.ink/2.ppx))
135 |
136 | 下载本项目:
137 | ```Bash
138 | git clone https://github.com/fhyuncai/24h-server-live-on-bilibili.git
139 | ```
140 |
141 | 配置项说明:
142 | ```Json
143 | {
144 | "path": "/root/24h-server-live-on-bilibili", //文件所在目录
145 | "musicapi": "https://api.yuncaioo.com/bililive/", //API地址
146 | "freespace": "15360", //允许下载和缓存文件夹占用空间大小,超过时自动按时间顺序删除音乐,单位:MiB
147 | "gift": "0", //设定是否使用投礼物才能点歌,0为关闭,1为开启
148 | "rtmp": {
149 | "url": "", //rtmp地址
150 | "code": "", //直播码
151 | "bitrate": "192" //推流码率,单位k
152 | },
153 | "danmu": {
154 | "cookie": "", //发送弹幕用的cookie
155 | "token": "", //发送弹幕用的csrf_token
156 | "roomid": "4059464", //直播间ID
157 | "size": "20" //每段弹幕的最大长度(20级以后可发30字)
158 | },
159 | "nightvideo": {
160 | "use": "1" //设定是否播放晚间专属视频,0为关闭,1为开启
161 | }
162 | }
163 | ```
164 |
165 | 请修改`Config.json`文件中的各种选项
166 |
167 | 其中,`cookie`请尽量使用小号,在直播间,打开浏览器审查元素,先发一条弹幕,再查看`network`选项卡,找到`name`为`send`的项目,`Request head`中的`Cookie`即为`cookie`变量的值。注意设置后,账号不能点击网页上的“退出登陆”按键,换账号请直接清除当前Cookie再刷新
168 |
169 | `token`请填写`Request head`中的`csrf_token`
170 |
171 | `service/PostDanmu.py`文件的`因缺思厅233333`请改为你的机器人的名字,`FH云彩`请改为你的名字
172 |
173 | 如有条件,请`务必`自己搭建php的下载链接解析服务,源码都在`tools/php`文件夹内(需要修改,请等待更新)
174 |
175 | `resource/music`文件夹内放入mp3格式的音乐,在无人点歌时播放
176 |
177 | `resource/img`文件夹内放入jpg格式的图片,用于做为放音乐时的背景,请尽量保证文件名全英文,分辨率推荐统一处理为1280x720
178 |
179 | 所有配置完成后,开启直播,然后启动脚本即可:
180 |
181 | ```Bash
182 | sh start.sh
183 | ```
184 |
185 | ### 其他命令
186 |
187 | 停止:
188 | ```Bash
189 | sh stop.sh
190 | ```
191 |
192 | 重启:
193 | ```Bash
194 | sh restart.sh
195 | ```
196 |
197 | 如有出错的地方,请提交issue,也欢迎各位改进脚本并pr
198 |
--------------------------------------------------------------------------------
/fonts/msyh.ttc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/fonts/msyh.ttc
--------------------------------------------------------------------------------
/log/Downloads.log:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/log/Downloads.log
--------------------------------------------------------------------------------
/resource/img/001.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/001.jpg
--------------------------------------------------------------------------------
/resource/img/002.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/002.jpg
--------------------------------------------------------------------------------
/resource/img/003.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/003.jpg
--------------------------------------------------------------------------------
/resource/img/004.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/004.jpg
--------------------------------------------------------------------------------
/resource/img/005.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/005.jpg
--------------------------------------------------------------------------------
/resource/img/006.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/006.jpg
--------------------------------------------------------------------------------
/resource/img/007.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/007.jpg
--------------------------------------------------------------------------------
/resource/img/008.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/008.jpg
--------------------------------------------------------------------------------
/resource/img/009.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/009.jpg
--------------------------------------------------------------------------------
/resource/img/010.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/010.jpg
--------------------------------------------------------------------------------
/resource/img/011.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/011.jpg
--------------------------------------------------------------------------------
/resource/img/012.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/012.jpg
--------------------------------------------------------------------------------
/resource/img/013.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/013.jpg
--------------------------------------------------------------------------------
/resource/img/014.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/014.jpg
--------------------------------------------------------------------------------
/resource/img/015.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/015.jpg
--------------------------------------------------------------------------------
/resource/img/016.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/016.jpg
--------------------------------------------------------------------------------
/resource/img/017.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/017.jpg
--------------------------------------------------------------------------------
/resource/img/018.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/img/018.jpg
--------------------------------------------------------------------------------
/resource/music/Kyle Xian - 永遠のひとつ(动画《ISLAND》OP)(Cover 田村ゆかり).mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/music/Kyle Xian - 永遠のひとつ(动画《ISLAND》OP)(Cover 田村ゆかり).mp3
--------------------------------------------------------------------------------
/resource/music/default.ass:
--------------------------------------------------------------------------------
1 | [Script Info]
2 | ; Script generated by Aegisub 3.2.2
3 | ; http://www.aegisub.org/
4 | Title: Default ASS file
5 | ScriptType: v4.00+
6 | WrapStyle: 2
7 | PlayResX: 960
8 | PlayResY: 720
9 | ScaledBorderAndShadow: yes
10 |
11 | [Aegisub Project Garbage]
12 | Video Zoom Percent: 1.000000
13 |
14 | [V4+ Styles]
15 | Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
16 | Style: Default,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,2,10,10,5,1
17 | Style: left_down,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,1,10,10,5,1
18 | Style: right_down,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,3,10,10,5,1
19 | Style: left_up,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,7,10,10,5,1
20 | Style: right_up,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,9,10,10,5,1
21 |
22 | [Events]
23 | Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
24 | Dialogue: 2,0:00:00.00,9:00:00.00,left_down,,0,0,0,,当前播放的是预置歌曲
25 | Dialogue: 2,0:00:00.00,9:00:00.00,right_down,,0,0,0,,基于阿里云服务器
26 | Dialogue: 2,0:00:00.00,9:00:00.00,left_up,,0,0,0,,FHYC的音乐台
27 | Dialogue: 2,0:00:00.00,9:00:00.00,right_up,,0,0,0,,
28 |
--------------------------------------------------------------------------------
/resource/music/堀江晶太 - Sincerely (off vocal).mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/music/堀江晶太 - Sincerely (off vocal).mp3
--------------------------------------------------------------------------------
/resource/night/default.ass:
--------------------------------------------------------------------------------
1 | [Script Info]
2 | ; Script generated by Aegisub 3.2.2
3 | ; http://www.aegisub.org/
4 | Title: Default ASS file
5 | ScriptType: v4.00+
6 | WrapStyle: 2
7 | PlayResX: 960
8 | PlayResY: 720
9 | ScaledBorderAndShadow: yes
10 |
11 | [Aegisub Project Garbage]
12 | Video Zoom Percent: 1.000000
13 | Active Line: 3
14 |
15 | [V4+ Styles]
16 | Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
17 | Style: Default,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,2,10,10,5,1
18 | Style: left_down,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,1,10,10,5,1
19 | Style: right_down,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,3,10,10,5,1
20 | Style: left_up,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,7,10,10,5,1
21 | Style: right_up,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100,100,0,0,1,3.55469,3,9,10,10,5,1
22 |
23 | [Events]
24 | Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
25 | Dialogue: 2,0:00:00.00,9:00:00.00,left_down,,0,0,0,,当前是晚间专属时间哦~时间范围:晚上23点-凌晨5点\N大家晚安哦~做个好梦~
26 | Dialogue: 2,0:00:00.00,9:00:00.00,right_down,,0,0,0,,基于阿里云服务器
27 | Dialogue: 2,0:00:00.00,9:00:00.00,left_up,,0,0,0,,FHYC的音乐台
28 | Dialogue: 2,0:00:00.00,9:00:00.00,right_up,,0,0,0,,
29 |
--------------------------------------------------------------------------------
/resource/playlist/empty_file:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/playlist/empty_file
--------------------------------------------------------------------------------
/resource/users/not_empty:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fhyuncai/Server-Music-Live-On-Bilibili/59042fa32046922bb9e5655af92b6c826da073a3/resource/users/not_empty
--------------------------------------------------------------------------------
/restart.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | sh stop.sh
4 | sh start.sh
--------------------------------------------------------------------------------
/service/AssMaker.py:
--------------------------------------------------------------------------------
1 | #coding:utf-8
2 | import os
3 | import time
4 | import re
5 | from mutagen.mp3 import MP3
6 | from moviepy.editor import VideoFileClip
7 |
8 |
9 |
10 | #生成字幕文件,传入参数:
11 | #filename:文件名
12 | #info:文件信息,用于左下角显示用的
13 | #path:文件路径
14 | #ass:最原始的歌词数据
15 | def make_ass(filename, info, path, ass = '', asst = ''):
16 | ass = lrc_to_ass(ass)
17 | asst = tlrc_to_ass(asst)
18 | timer_get = timer_create(filename,path)
19 | file_content = '''[Script Info]
20 | Title: Default ASS file
21 | ScriptType: v4.00+
22 | WrapStyle: 2
23 | Collisions: Normal
24 | PlayResX: 960
25 | PlayResY: 720
26 | ScaledBorderAndShadow: yes
27 | Video Zoom Percent: 1
28 |
29 | [V4+ Styles]
30 | Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
31 | Style: Default,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,2,10,10,5,1
32 | Style: left_down,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,1,10,10,5,1
33 | Style: right_down,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,3,10,10,5,1
34 | Style: left_up,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,7,10,10,5,1
35 | Style: right_up,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,9,10,10,5,1
36 | Style: center_up,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,8,10,10,5,1
37 | Style: center_up_big,微软雅黑,28,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,8,10,10,5,1
38 | Style: center_down,微软雅黑,20,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,2,10,10,5,1
39 | Style: center_down_big,微软雅黑,28,&H00FFFFFF,&H00FFFFFF,&H28533B3B,&H500E0A00,0,0,0,0,100.0,100.0,0.0,0.0,1,3.5546875,3.0,2,10,10,5,1
40 |
41 | [Events]
42 | Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
43 | Dialogue: 2,0:00:00.00,9:00:00.00,left_down,,0,0,0,,'''+info+'''
44 | Dialogue: 2,0:00:00.00,9:00:00.00,right_down,,0,0,0,,基于阿里云服务器''''''
45 | Dialogue: 2,0:00:00.00,9:00:00.00,left_up,,0,0,0,,FHYC的音乐台
46 | Dialogue: 2,0:00:00.00,9:00:00.00,right_up,,0,0,0,,
47 | '''+ass+asst+timer_get #44行文字后第3处 \\N +'点播日期:'+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+
48 | file = open(path+'/resource/playlist/'+str(filename)+'.ass','w') #保存ass字幕文件
49 | file.write(file_content)
50 | file.close()
51 |
52 | #生成info文件
53 | def make_info(filename, info, path):
54 | file_content = info
55 | file = open(path+'/resource/playlist/'+str(filename)+'.info','w')
56 | file.write(file_content)
57 | file.close()
58 |
59 | def s3t(sec):
60 | m, s = divmod(sec, 60)
61 | h, m = divmod(m, 60)
62 | return ("%01d:%02d:%02d" % (h, m, s))
63 |
64 | def timer_create(filename, path):
65 | result='\r\n'
66 | filename = filename.replace('ok','')
67 | if(os.path.isfile(path+'/resource/playlist/'+str(filename)+'.mp3')):
68 | try:
69 | audio = MP3(path+'/resource/playlist/'+str(filename)+'.mp3') #获取mp3文件信息
70 | seconds=int(audio.info.length) #获取时长
71 | for i in range(1, seconds):
72 | result+='Dialogue: 2,'+s3t(i-1)+'.00,'+s3t(i)+'.00,right_down,,0,0,0,,歌曲时间:'+s3t(i)+'/'+s3t(seconds)+'\r\n'
73 | except Exception as e:
74 | print('shit')
75 | print(e)
76 | # else:
77 | # try:
78 | # if(os.path.isfile(path+'/resource/playlist/'+str(filename)+'.mp4')): #获取视频文件信息
79 | # print(path+'/resource/playlist/'+str(filename)+'.mp4')
80 | # vv = VideoFileClip(path+'/resource/playlist/'+str(filename)+'.mp4')
81 | # seconds=int(vv.duration) #获取时长
82 | # print('time seconds:'+str(seconds))
83 | # for i in range(1, seconds):
84 | # result+='Dialogue: 2,'+s3t(i-1)+'.00,'+s3t(i)+'.00,right_down,,0,0,0,,视频时间:'+s3t(i)+'/'+s3t(seconds)+'\r\n'
85 | # elif(os.path.isfile(path+'/resource/playlist/'+str(filename)+'rendering1.flv')):
86 | # print(path+'/resource/playlist/'+str(filename)+'rendering1.flv')
87 | # vv = VideoFileClip(path+'/resource/playlist/'+str(filename)+'rendering1.flv')
88 | # seconds=int(vv.duration) #获取时长
89 | # print('time seconds:'+str(seconds))
90 | # for i in range(1, seconds):
91 | # result+='Dialogue: 2,'+s3t(i-1)+'.00,'+s3t(i)+'.00,right_down,,0,0,0,,视频时间:'+s3t(i)+'/'+s3t(seconds)+'\r\n'
92 | # elif(os.path.isfile(path+'/resource/playlist/'+str(filename)+'rendering1.mp4')):
93 | # print(path+'/resource/playlist/'+str(filename)+'rendering1.mp4')
94 | # vv = VideoFileClip(path+'/resource/playlist/'+str(filename)+'rendering1.mp4')
95 | # seconds=int(vv.duration) #获取时长
96 | # print('time seconds:'+str(seconds))
97 | # for i in range(1, seconds):
98 | # result+='Dialogue: 2,'+s3t(i-1)+'.00,'+s3t(i)+'.00,right_down,,0,0,0,,视频时间:'+s3t(i)+'/'+s3t(seconds)+'\r\n'
99 | # else:
100 | # print('no files found!')
101 | # print(path+'/resource/playlist/'+str(filename))
102 | # except Exception as e:
103 | # print('shit')
104 | # print(e)
105 | return result
106 |
107 |
108 | #滚动歌词生成
109 | def lrc_to_ass(lrc):
110 | lrc=lrc.splitlines() #按行分割开来
111 | list1=['00','00']
112 | list2=['00','00']
113 | list3=['00','00']
114 | list4=[' ',' ']
115 | result='\r\n'
116 | for i in lrc:
117 | matchObj = re.match( r'.*\[(\d+):(\d+)\.(\d+)\]([^\[\]]*)', i) #正则匹配获取每行的参数,看不懂的去自行学习正则表达式
118 | if matchObj: #如果匹配到了东西
119 | list1.append(matchObj.group(1))
120 | list2.append(matchObj.group(2))
121 | list3.append(matchObj.group(3))
122 | list4.append(matchObj.group(4))
123 | list1.append('05')
124 | list1.append('05')
125 | list2.append('00')
126 | list2.append('00')
127 | list3.append('00')
128 | list3.append('00')
129 | list4.append(' ')
130 | list4.append(' ')
131 | for i in range(2, len(list1)-4):
132 | text=' '+list4[i+1]+' \\N '+list4[i+2]+' '
133 | result+='Dialogue: 2,0:'+list1[i]+':'+list2[i]+'.'+list3[i][0:2]+',0:'+list1[i+1]+':'+list2[i+1]+'.'+list3[i+1][0:2]+',center_down,,0,0,0,,'+text+'\r\n'
134 | text=' '+list4[i]+' '
135 | result+='Dialogue: 2,0:'+list1[i]+':'+list2[i]+'.'+list3[i][0:2]+',0:'+list1[i+1]+':'+list2[i+1]+'.'+list3[i+1][0:2]+',center_down_big,,0,0,0,,'+text+'\r\n'
136 | text=' '+list4[i-2]+' \\N '+list4[i-1]+' '
137 | result+='Dialogue: 2,0:'+list1[i]+':'+list2[i]+'.'+list3[i][0:2]+',0:'+list1[i+1]+':'+list2[i+1]+'.'+list3[i+1][0:2]+',center_down,,0,0,0,,'+text+'\r\n'
138 | #修正倒数第二句句歌词消失的bug
139 | text=' '+list4[len(list1)-3]+' \\N '+list4[len(list1)-2]+' '
140 | result+='Dialogue: 2,0:'+list1[len(list1)-4]+':'+list2[len(list1)-4]+'.'+list3[len(list1)-4][0:2]+',0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',center_down,,0,0,0,,'+text+'\r\n'
141 | text=' '+list4[len(list1)-4]+' '
142 | result+='Dialogue: 2,0:'+list1[len(list1)-4]+':'+list2[len(list1)-4]+'.'+list3[len(list1)-4][0:2]+',0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',center_down_big,,0,0,0,,'+text+'\r\n'
143 | text=' '+list4[len(list1)-6]+' \\N '+list4[len(list1)-5]+' '
144 | result+='Dialogue: 2,0:'+list1[len(list1)-4]+':'+list2[len(list1)-4]+'.'+list3[len(list1)-4][0:2]+',0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',center_down,,0,0,0,,'+text+'\r\n'
145 | #修正最后一句歌词消失的bug
146 | text=' '+list4[len(list1)-2]+' \\N '+list4[len(list1)-1]+' '
147 | result+='Dialogue: 2,0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',0:10:00.00,center_down,,0,0,0,,'+text+'\r\n'
148 | text=' '+list4[len(list1)-3]+' '
149 | result+='Dialogue: 2,0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',0:10:00.00,center_down_big,,0,0,0,,'+text+'\r\n'
150 | text=' '+list4[len(list1)-5]+' \\N '+list4[len(list1)-4]+' '
151 | result+='Dialogue: 2,0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',0:10:00.00,center_down,,0,0,0,,'+text+'\r\n'
152 | return result
153 |
154 |
155 | #滚动歌词生成
156 | def tlrc_to_ass(lrc):
157 | lrc=lrc.splitlines() #按行分割开来
158 | list1=['00','00']
159 | list2=['00','00']
160 | list3=['00','00']
161 | list4=[' ',' ']
162 | result='\r\n'
163 | for i in lrc:
164 | matchObj = re.match( r'.*\[(\d+):(\d+)\.(\d+)\]([^\[\]]*)', i) #正则匹配获取每行的参数,看不懂的去自行学习正则表达式
165 | if matchObj: #如果匹配到了东西
166 | list1.append(matchObj.group(1))
167 | list2.append(matchObj.group(2))
168 | list3.append(matchObj.group(3))
169 | list4.append(matchObj.group(4))
170 | list1.append('05')
171 | list1.append('05')
172 | list2.append('00')
173 | list2.append('00')
174 | list3.append('00')
175 | list3.append('00')
176 | list4.append(' ')
177 | list4.append(' ')
178 | for i in range(2, len(list1)-4):
179 | text=' '+list4[i-2]+' \\N '+list4[i-1]+' '
180 | result+='Dialogue: 2,0:'+list1[i]+':'+list2[i]+'.'+list3[i][0:2]+',0:'+list1[i+1]+':'+list2[i+1]+'.'+list3[i+1][0:2]+',center_up,,0,0,0,,'+text+'\r\n'
181 | text=' '+list4[i]+' '
182 | result+='Dialogue: 2,0:'+list1[i]+':'+list2[i]+'.'+list3[i][0:2]+',0:'+list1[i+1]+':'+list2[i+1]+'.'+list3[i+1][0:2]+',center_up_big,,0,0,0,,'+text+'\r\n'
183 | text=' '+list4[i+1]+' \\N '+list4[i+2]+' '
184 | result+='Dialogue: 2,0:'+list1[i]+':'+list2[i]+'.'+list3[i][0:2]+',0:'+list1[i+1]+':'+list2[i+1]+'.'+list3[i+1][0:2]+',center_up,,0,0,0,,'+text+'\r\n'
185 | #修正倒数第二句句歌词消失的bug
186 | text=' '+list4[len(list1)-6]+' \\N '+list4[len(list1)-5]+' '
187 | result+='Dialogue: 2,0:'+list1[len(list1)-4]+':'+list2[len(list1)-4]+'.'+list3[len(list1)-4][0:2]+',0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',center_up,,0,0,0,,'+text+'\r\n'
188 | text=' '+list4[len(list1)-4]+' '
189 | result+='Dialogue: 2,0:'+list1[len(list1)-4]+':'+list2[len(list1)-4]+'.'+list3[len(list1)-4][0:2]+',0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',center_up_big,,0,0,0,,'+text+'\r\n'
190 | text=' '+list4[len(list1)-3]+' \\N '+list4[len(list1)-2]+' '
191 | result+='Dialogue: 2,0:'+list1[len(list1)-4]+':'+list2[len(list1)-4]+'.'+list3[len(list1)-4][0:2]+',0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',center_up,,0,0,0,,'+text+'\r\n'
192 | #修正最后一句歌词消失的bug
193 | text=' '+list4[len(list1)-5]+' \\N '+list4[len(list1)-4]+' '
194 | result+='Dialogue: 2,0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',0:10:00.00,center_up,,0,0,0,,'+text+'\r\n'
195 | text=' '+list4[len(list1)-3]+' '
196 | result+='Dialogue: 2,0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',0:10:00.00,center_up_big,,0,0,0,,'+text+'\r\n'
197 | text=' '+list4[len(list1)-2]+' \\N '+list4[len(list1)-1]+' '
198 | result+='Dialogue: 2,0:'+list1[len(list1)-3]+':'+list2[len(list1)-3]+'.'+list3[len(list1)-3][0:2]+',0:10:00.00,center_up,,0,0,0,,'+text+'\r\n'
199 | return result
200 |
--------------------------------------------------------------------------------
/service/GetInfo.py:
--------------------------------------------------------------------------------
1 | #coding:utf-8
2 | import os
3 |
4 | # Return CPU temperature as a character string
5 | def getCPUtemperature():
6 | res = os.popen('vcgencmd measure_temp').readline()
7 | return(res.replace("temp=","").replace("'C\n",""))
8 |
9 | # Return RAM information (unit=kb) in a list
10 | # Index 0: total RAM
11 | # Index 1: used RAM
12 | # Index 2: free RAM
13 | def getRAMinfo():
14 | p = os.popen('free')
15 | i = 0
16 | while 1:
17 | i = i + 1
18 | line = p.readline()
19 | if i==2:
20 | return(line.split()[1:4])
21 |
22 | # Return % of CPU used by user as a character string
23 | def getCPUuse():
24 | return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
25 |
26 | # Return information about disk space as a list (unit included)
27 | # Index 0: total disk space
28 | # Index 1: used disk space
29 | # Index 2: remaining disk space
30 | # Index 3: percentage of disk used
31 | def getDiskSpace():
32 | p = os.popen("df -h /")
33 | i = 0
34 | while 1:
35 | i = i +1
36 | line = p.readline()
37 | if i==2:
38 | return(line.split()[1:5])
39 |
40 | def getInfo():
41 | # CPU informatiom
42 | CPU_temp = getCPUtemperature()
43 | CPU_usage = getCPUuse()
44 |
45 | # RAM information
46 | # Output is in kb, here I convert it in Mb for readability
47 | RAM_stats = getRAMinfo()
48 | RAM_total = round(int(RAM_stats[0]) / 1000,1)
49 | RAM_used = round(int(RAM_stats[1]) / 1000,1)
50 | RAM_free = round(int(RAM_stats[2]) / 1000,1)
51 |
52 | # Disk information
53 | DISK_stats = getDiskSpace()
54 | DISK_total = DISK_stats[0]
55 | DISK_used = DISK_stats[1]
56 | DISK_perc = DISK_stats[3]
57 |
58 | print('')
59 | print('CPU Temperature = '+CPU_temp)
60 | print('CPU Use = '+CPU_usage)
61 | print('')
62 | print('RAM Total = '+str(RAM_total)+' MB')
63 | print('RAM Used = '+str(RAM_used)+' MB')
64 | print('RAM Free = '+str(RAM_free)+' MB')
65 | print('')
66 | print('DISK Total Space = '+str(DISK_total)+'B')
67 | print('DISK Used Space = '+str(DISK_used)+'B')
68 | print('DISK Used Percentage = '+str(DISK_perc))
69 | return 'CPU占用:'+CPU_usage+'%,内存占用:'+str(int(RAM_used))+'MB,磁盘占用:'+str(DISK_perc) #CPU温度:'+CPU_temp+'℃,
70 |
--------------------------------------------------------------------------------
/service/PostDanmu.py:
--------------------------------------------------------------------------------
1 | #coding:utf-8
2 | import urllib
3 | import urllib.request
4 | import http.cookiejar
5 | import json
6 | import time
7 | import os
8 | import sys
9 | import datetime
10 | import time
11 | import service.AssMaker
12 | #import Config
13 | import _thread
14 | import random
15 | import service.GetInfo
16 | import numpy
17 |
18 | config = json.load(open('./Config.json', encoding='utf-8'))
19 | path = config['path']
20 | roomid = config['danmu']['roomid']
21 | cookie = config['danmu']['cookie']
22 | csrf_token = config['danmu']['token']
23 | download_api_url = config['musicapi']
24 |
25 | dm_lock = False #弹幕发送锁,用来排队
26 | encode_lock = False #视频渲染锁,用来排队
27 |
28 | sensitive_word = ('64', '89') #容易误伤的和谐词汇表,待补充
29 |
30 | #用于删除文件,防止报错
31 | def del_file(f):
32 | try:
33 | print('delete'+path+'/resource/playlist/'+f)
34 | os.remove(path+'/resource/playlist/'+f)
35 | except:
36 | print('delete error')
37 |
38 | #用于删除文件,防止报错
39 | def del_file_default_mp3(f):
40 | try:
41 | print('delete'+path+'/resource/music/'+f)
42 | os.remove(path+'/resource/music/'+f)
43 | except:
44 | print('delete error')
45 |
46 | #检查已使用空间是否超过设置大小
47 | def check_free():
48 | files = os.listdir(path+'/resource/playlist') #获取下载文件夹下所有文件
49 | size = 0
50 | for f in files: #遍历所有文件
51 | size += os.path.getsize(path+'/resource/playlist/'+f) #累加大小
52 | files = os.listdir(path+'/resource/music')#获取缓存文件夹下所有文件
53 | for f in files: #遍历所有文件
54 | size += os.path.getsize(path+'/resource/music/'+f)#累加大小
55 | if(size > int(config['freespace'])*1024*1024): #判断是否超过设定大小
56 | print("space size:"+str(size))
57 | return True
58 | else:
59 | return False
60 |
61 | #检查已使用空间,并在超过时,自动删除缓存的视频
62 | def clean_files():
63 | is_boom = True #用来判断可用空间是否爆炸
64 | if(check_free()): #检查已用空间是否超过设置大小
65 | files = os.listdir(path+'/resource/music') #获取下载文件夹下所有文件
66 | files.sort() #排序文件,以便按日期删除多余文件
67 | for f in files:
68 | if((f.find('.flv') != -1) & (check_free())): #检查可用空间是否依旧超过设置大小,flv文件
69 | del_file_default_mp3(f) #删除文件
70 | elif((f.find('.mp3') != -1) & (check_free())): #检查可用空间是否依旧超过设置大小,mp3文件
71 | del_file_default_mp3(f) #删除文件
72 | del_file_default_mp3(f.replace(".mp3",'')+'.ass')
73 | del_file_default_mp3(f.replace(".mp3",'')+'.info')
74 | elif(check_free() == False): #符合空间大小占用设置时,停止删除操作
75 | is_boom = False
76 | else:
77 | is_boom = False
78 | return is_boom
79 |
80 |
81 | #下载歌曲,传入参数:
82 | #s:数值型,传入歌曲/mv的id
83 | #t:type,类型,mv或id
84 | #user:字符串型,点播者
85 | #song:歌名,点播时用的关键字,可选
86 | def get_download_url(s, t, user, song = "nothing"):
87 | if(clean_files()): #检查空间是否在设定值以内,并自动删除多余视频缓存
88 | send_dm_long('Server存储空间已爆炸,请联系up')
89 | return
90 | if bool(int(config['gift'])) and check_coin(user, 100) == False:
91 | send_dm_long('用户'+user+'赠送的瓜子不够点歌哦,还差'+str(100-get_coin(user))+'瓜子的礼物')
92 | return
93 | send_dm_long('正在下载ID'+str(s))
94 | print('[log]getting url:ID'+str(s))
95 | try:
96 | filename = str(time.mktime(datetime.datetime.now().timetuple())) #获取时间戳,用来当作文件名
97 | urllib.request.urlretrieve(urllib.request.urlopen(download_api_url + "?%s" % urllib.parse.urlencode({'id': s}),timeout=5).read().decode('utf-8'), path+'/resource/playlist/'+filename+'.mp3') #下载歌曲 "http://music.163.com/song/media/outer/url?id="+str(s)+".mp3"
98 | print('[log]downloaded:ID'+str(s))
99 | lyric = urllib.request.urlopen(download_api_url + "?%s" % urllib.parse.urlencode({'lyric': s}),timeout=5).read().decode('utf-8') #设定获取歌词的网址
100 |
101 | tlyric = urllib.request.urlopen(download_api_url + "?%s" % urllib.parse.urlencode({'tlyric': s}),timeout=5).read().decode('utf-8') #设定获取歌词的网址
102 | print('[log]got lyric:ID'+str(s))
103 | name = urllib.request.urlopen(download_api_url + "?%s" % urllib.parse.urlencode({'name': s}),timeout=5).read().decode('utf-8') #设定获取歌词的网址
104 | print('[log]got name:ID'+str(s))
105 | if(song == "nothing"): #当直接用id点歌时
106 | service.AssMaker.make_ass(filename,'歌曲网易云ID:'+str(s)+'\\N歌曲名:'+str(name)+"\\N点播人:"+user,path,lyric,tlyric) #生成字幕
107 | service.AssMaker.make_info(filename,'ID:'+str(s)+',名称:'+str(name)+",点播人:"+user,path) #生成介绍信息,用来查询
108 | else: #当用关键字搜索点歌时
109 | service.AssMaker.make_ass(filename,'歌曲网易云ID:'+str(s)+'\\N歌曲名:'+str(name)+"\\N点播关键词:"+song+"\\N点播人:"+user,path,lyric,tlyric) #生成字幕
110 | service.AssMaker.make_info(filename,'ID:'+str(s)+',名称:'+str(name)+",关键词:"+song+",点播人:"+user,path) #生成介绍信息,用来查询
111 | send_dm_long('ID'+str(s)+'下载完成,已加入播放队列')
112 | print('[log]已添加排队项目:ID'+str(s))
113 |
114 | try: #记录日志,已接近废弃
115 | log_file = open(path+'/log/Downloads.log', 'a')
116 | log_file.writelines(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + ','+user+','+t+str(s)+'\r\n')
117 | log_file.close()
118 | except:
119 | print('[error]log error')
120 | except: #下载出错
121 | send_dm_long('出错了:请检查命令或重试')
122 | if bool(int(config['gift'])): #归还用掉的瓜子
123 | give_coin(user,100)
124 | print('[log]下载文件出错:ID'+str(s))
125 | del_file(filename+'.mp3')
126 |
127 | #下载歌单
128 | def playlist_download(id,user):
129 | params = urllib.parse.urlencode({'playlist': str(id)}) #格式化参数
130 | f = urllib.request.urlopen(download_api_url + "?%s" % params,timeout=3) #设定获取的网址
131 | try:
132 | playlist = json.loads(f.read().decode('utf-8')) #获取结果,并反序化
133 | if len(playlist['playlist']['tracks'])*100 > get_coin(user) and bool(int(config['gift'])):
134 | send_dm_long('用户'+user+'赠送的瓜子不够点'+str(len(playlist['playlist']['tracks']))+
135 | '首歌哦,还差'+str(len(playlist['playlist']['tracks'])*100-get_coin(user))+'瓜子的礼物')
136 | return
137 | else:
138 | send_dm_long('正在下载歌单:'+playlist['playlist']['name']+',共'+str(len(playlist['playlist']['tracks']))+'首')
139 | except Exception as e: #防炸
140 | print('shit')
141 | print(e)
142 | send_dm_long('出错了:请检查命令或重试')
143 | for song in playlist['playlist']['tracks']:
144 | print('name:'+song['name']+'id:'+str(song['id']))
145 | get_download_url(song['id'], 'id', user, song['name'])
146 |
147 | #搜索歌曲并下载
148 | def search_song(s,user):
149 | print('[log]searching song:'+s)
150 | params = urllib.parse.urlencode({'type': 1, 's': s}) #格式化参数
151 | f = urllib.request.urlopen("http://s.music.163.com/search/get/?%s" % params,timeout=3) #设置接口网址
152 | search_result = json.loads(f.read().decode('utf-8')) #获取结果
153 | result_id = search_result["result"]["songs"][0]["id"] #提取歌曲id
154 | _thread.start_new_thread(get_download_url, (result_id, 'id', user,s)) #扔到下载那里下载
155 |
156 | #获取赠送过的瓜子数量
157 | def get_coin(user):
158 | gift_count = 0
159 | try:
160 | gift_count = numpy.load('../resource/users/'+user+'.npy')
161 | except:
162 | gift_count = 0
163 | return gift_count
164 |
165 | #扣除赠送过的瓜子数量
166 | def take_coin(user, take_sum):
167 | gift_count = 0
168 | try:
169 | gift_count = numpy.load('../resource/users/'+user+'.npy')
170 | except:
171 | gift_count = 0
172 | gift_count = gift_count - take_sum
173 | try:
174 | numpy.save('../resource/users/'+user+'.npy', gift_count)
175 | except:
176 | print('create error')
177 |
178 | #检查并扣除指定数量的瓜子
179 | def check_coin(user, take_sum):
180 | if get_coin(user) >= take_sum:
181 | take_coin(user, take_sum)
182 | return True
183 | else:
184 | return False
185 |
186 | #给予赠送过的瓜子数量
187 | def give_coin(user, give_sum):
188 | gift_count = 0
189 | try:
190 | gift_count = numpy.load('../resource/users/'+user+'.npy')
191 | except:
192 | gift_count = 0
193 | gift_count = gift_count + give_sum
194 | try:
195 | numpy.save('../resource/users/'+user+'.npy', gift_count)
196 | except:
197 | print('create error')
198 |
199 | def check_night():
200 | print(time.localtime()[3])
201 | if (time.localtime()[3] <= 5) and config['nightvideo']['use']: #time.localtime()[3] >= 23 or
202 | send_dm_long('现在是晚间专场哦~命令无效')
203 | return True
204 |
205 | #切歌请求次数统计
206 | jump_to_next_counter = 0
207 | rp_lock = False
208 | def pick_msg(s, user):
209 | global jump_to_next_counter #切歌请求次数统计
210 | global encode_lock #视频渲染任务锁
211 | global rp_lock
212 | if ((user=='FH云彩')): #debug使用,请自己修改
213 | if(s=='锁定'):
214 | rp_lock = True
215 | send_dm_long('已锁定点播功能,不响应任何弹幕')
216 | if(s=='解锁'):
217 | rp_lock = False
218 | send_dm_long('已解锁点播功能,开始响应弹幕请求')
219 | if((user == '因缺思厅233333') | rp_lock): #防止自循环
220 | return
221 | #下面的不作解释,很简单一看就懂
222 | if (s.find('id+') == 0):
223 | if check_night():
224 | return
225 | send_dm_long('已收到'+user+'的指令')
226 | s = s.replace(' ', '') #剔除弹幕中的所有空格
227 | _thread.start_new_thread(get_download_url, (s.replace('id+', '', 1), 'id',user))
228 | elif (s.find('song+') == 0):
229 | if check_night():
230 | return
231 | try:
232 | send_dm_long('已收到'+user+'的指令')
233 | search_song(s.replace('song+', '', 1),user)
234 | except:
235 | print('[log]song not found')
236 | send_dm_long('出错了:没这首歌')
237 | elif (s.find('id') == 0):
238 | if check_night():
239 | return
240 | send_dm_long('已收到'+user+'的指令')
241 | s = s.replace(' ', '') #剔除弹幕中的所有空格
242 | _thread.start_new_thread(get_download_url, (s.replace('id', '', 1), 'id',user))
243 | elif (s.find('song') == 0):
244 | if check_night():
245 | return
246 | try:
247 | send_dm_long('已收到'+user+'的指令')
248 | search_song(s.replace('song', '', 1),user)
249 | except:
250 | print('[log]song not found')
251 | send_dm_long('出错了:没这首歌')
252 | elif (s.find('点歌') == 0):
253 | if check_night():
254 | return
255 | try:
256 | send_dm_long('已收到'+user+'的指令')
257 | search_song(s.replace('点歌', '', 1),user)
258 | except:
259 | print('[log]song not found')
260 | send_dm_long('出错了:没这首歌')
261 | elif (s.find('喵') > -1):
262 | replay = ["喵??", "喵喵!", "喵。。喵?", "喵喵喵~", "喵!"]
263 | send_dm_long(replay[random.randint(0, len(replay)-1)]) #用于测试是否崩掉
264 | elif (s == '切歌'): #切歌请求
265 | jump_to_next_counter += 1 #切歌次数统计加一
266 | if((user=='FH云彩')): #debug使用,请自己修改
267 | jump_to_next_counter=5
268 | if(jump_to_next_counter < 5): #次数未达到五次
269 | send_dm_long('已收到'+str(jump_to_next_counter)+'次切歌请求,达到五次将切歌')
270 | else: #次数未达到五次
271 | jump_to_next_counter = 0 #次数统计清零
272 | send_dm_long('已执行切歌动作')
273 | os.system('killall ffmpeg') #强行结束ffmpeg进程
274 | elif ((s == '点播列表') or (s == '歌曲列表') or (s == '列表')):
275 | if check_night():
276 | return
277 | send_dm_long('已收到'+user+'的指令,正在查询')
278 | files = os.listdir(path+'/resource/playlist') #获取目录下所有文件
279 | files.sort() #按文件名(下载时间)排序
280 | songs_count = 0 #项目数量
281 | all_the_text = ""
282 | for f in files:
283 | if((f.find('.mp3') != -1) and (f.find('.download') == -1)): #如果是mp3文件
284 | try:
285 | info_file = open(path+'/resource/playlist/'+f.replace(".mp3",'')+'.info', 'r') #读取相应的info文件
286 | all_the_text = info_file.read()
287 | info_file.close()
288 | except Exception as e:
289 | print(e)
290 | if(songs_count < 10):
291 | send_dm_long(all_the_text)
292 | songs_count += 1
293 | if(songs_count <= 10):
294 | send_dm_long('点播列表展示完毕,一共'+str(songs_count)+'个')
295 | else:
296 | send_dm_long('点播列表前十个展示完毕,一共'+str(songs_count)+'个')
297 | elif (s.find('歌单') == 0):
298 | if check_night():
299 | return
300 | send_dm_long('已收到'+user+'的指令')
301 | s = s.replace(' ', '') #剔除弹幕中的所有空格
302 | _thread.start_new_thread(playlist_download, (s.replace('歌单', '', 1),user))
303 | elif (s.find('查询') == 0):
304 | send_dm_long(user+'的瓜子余额还剩'+str(get_coin(user))+'个')
305 | # else:
306 | # print('not match anything')
307 |
308 |
309 |
310 |
311 |
312 | #发送弹幕函数,通过post完成,具体可以自行使用浏览器,进入审查元素,监控network选项卡研究
313 | def send_dm(s):
314 | global cookie
315 | global roomid
316 | global dm_lock
317 | global csrf_token
318 | while (dm_lock):
319 | #print('[log]wait for send dm')
320 | time.sleep(1)
321 | dm_lock = True
322 | try:
323 | url = "https://api.live.bilibili.com/msg/send"
324 | postdata =urllib.parse.urlencode({
325 | 'color':'16777215',
326 | 'fontsize':'25',
327 | 'mode':'1',
328 | 'msg':s,
329 | 'rnd':'1510756027',
330 | 'roomid':roomid,
331 | 'csrf_token':csrf_token
332 | }).encode('utf-8')
333 | header = {
334 | "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
335 | "Accept-Encoding":"utf-8",
336 | "Accept-Language":"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
337 | "Connection":"keep-alive",
338 | "Cookie":cookie,
339 | "Host":"api.live.bilibili.com",
340 | "Referer":"http://live.bilibili.com/"+roomid,
341 | "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
342 | }
343 | req = urllib.request.Request(url,postdata,header)
344 | dm_result = json.loads(urllib.request.urlopen(req,timeout=3).read().decode('utf-8'))
345 | if len(dm_result['msg']) > 0:
346 | print('[error]弹幕发送失败:'+s)
347 | print(dm_result)
348 | else:
349 | print('[log]发送弹幕:'+s)
350 | except:
351 | print('[error]send dm error')
352 | time.sleep(1.5)
353 | dm_lock = False
354 |
355 | #每条弹幕最长只能发送20字符,过长的弹幕分段发送
356 | def send_dm_long(s):
357 | n=int(config['danmu']['size'])
358 | for hx in sensitive_word: #处理和谐词,防止点播机的回复被和谐
359 | if (s.find(hx) > -1):
360 | s = s.replace(hx, hx[0]+"-"+hx[1:]) #在和谐词第一个字符后加上一个空格
361 | for i in range(0, len(s), n):
362 | send_dm(s[i:i+n])
363 |
364 | #获取原始弹幕数组
365 | #本函数不作注释,具体也请自己通过浏览器审查元素研究
366 | def get_dm():
367 | global temp_dm
368 | global roomid
369 | global csrf_token
370 | url = "http://api.live.bilibili.com/ajax/msg"
371 | postdata =urllib.parse.urlencode({
372 | 'token:':'',
373 | 'csrf_token:':csrf_token,
374 | 'roomid':roomid
375 | }).encode('utf-8')
376 | header = {
377 | "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
378 | "Accept-Encoding":"utf-8",
379 | "Accept-Language":"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
380 | "Connection":"keep-alive",
381 | "Host":"api.live.bilibili.com",
382 | "Referer":"http://live.bilibili.com/"+roomid,
383 | "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
384 | }
385 | req = urllib.request.Request(url,postdata,header)
386 | dm_result = json.loads(urllib.request.urlopen(req,timeout=1).read().decode('utf-8'))
387 | #for t_get in dm_result['data']['room']:
388 | #print('[log]['+t_get['timeline']+']'+t_get['nickname']+':'+t_get['text'])
389 | return dm_result
390 |
391 | #检查某弹幕是否与前一次获取的弹幕数组有重复
392 | def check_dm(dm):
393 | global temp_dm
394 | for t_get in temp_dm['data']['room']:
395 | if((t_get['text'] == dm['text']) & (t_get['timeline'] == dm['timeline'])):
396 | return False
397 | return True
398 |
399 | #弹幕获取函数,原理为不断循环获取指定直播间的初始弹幕,并剔除前一次已经获取到的弹幕,余下的即为新弹幕
400 | def get_dm_loop():
401 | global temp_dm
402 | temp_dm = get_dm()
403 | while True:
404 | dm_result = get_dm()
405 | for t_get in dm_result['data']['room']:
406 | if(check_dm(t_get)):
407 | print('[log]['+t_get['timeline']+']'+t_get['nickname']+':'+t_get['text'])
408 | #send_dm('用户'+t_get['nickname']+'发送了'+t_get['text']) #别开,会死循环
409 | text = t_get['text']
410 | pick_msg(text,t_get['nickname']) #新弹幕检测是否匹配为命令
411 | temp_dm = dm_result
412 | time.sleep(1)
413 |
414 | def test():
415 | print('ok')
416 |
417 | print('程序已启动,连接房间id:'+roomid)
418 | # send_dm_long('弹幕监控已启动,可以点歌了')
419 | # while True: #防炸
420 | # try:
421 | # get_dm_loop() #开启弹幕获取循环函数
422 | # except Exception as e: #防炸
423 | # print('shit')
424 | # print(e)
425 | # dm_lock = False #解开弹幕锁,以免因炸了而导致弹幕锁没解开,进而导致一直锁着发不出弹幕
426 |
--------------------------------------------------------------------------------
/start.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | screen -S BiliMusic-Push -dm python3 Push.py
4 | screen -S BiliMusic-Danmu -dm python3 Danmu.py
--------------------------------------------------------------------------------
/stop.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | screen -S BiliMusic-Push -X quit
4 | screen -S BiliMusic-Danmu -X quit
--------------------------------------------------------------------------------
/tools/php/NeteaseMusicAPI_mini.php:
--------------------------------------------------------------------------------
1 | aes_encode(json_encode($raw),$this->_NONCE);
32 | $data['params']=$this->aes_encode($data['params'],$this->_secretKey);
33 | $data['encSecKey']=$this->_encSecKey;
34 | return $data;
35 | }
36 | protected function aes_encode($secretData,$secret){
37 | return openssl_encrypt($secretData,'aes-128-cbc',$secret,false,$this->_VI);
38 | }
39 |
40 | // CURL
41 | protected function curl($url,$data=null){
42 | $curl=curl_init();
43 | curl_setopt($curl,CURLOPT_URL,$url);
44 | if($data){
45 | if(is_array($data))$data=http_build_query($data);
46 | curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
47 | curl_setopt($curl,CURLOPT_POST,1);
48 | }
49 | curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);
50 | curl_setopt($curl,CURLOPT_CONNECTTIMEOUT, 10);
51 | curl_setopt($curl,CURLOPT_REFERER,$this->_REFERER);
52 | curl_setopt($curl,CURLOPT_COOKIE,$this->_COOKIE);
53 | curl_setopt($curl,CURLOPT_USERAGENT,$this->_USERAGENT);
54 | $result=curl_exec($curl);
55 | curl_close($curl);
56 | return $result;
57 | }
58 |
59 | // main function
60 | public function search($s,$limit=30,$offset=0,$type=1){
61 | $url='http://music.163.com/weapi/cloudsearch/get/web?csrf_token=';
62 | $data=array(
63 | 's'=>$s,
64 | 'type'=>$type,
65 | 'limit'=>$limit,
66 | 'total'=>'true',
67 | 'offset'=>$offset,
68 | 'csrf_token'=>'',
69 | );
70 | $raw=$this->curl($url,$this->prepare($data));
71 | if($this->_MINI_MODE){
72 | $this->_MINI_MODE=false;
73 | $raw=json_decode($raw,1);
74 | return json_encode($this->clear_data($raw["result"]["songs"]));
75 | }
76 | else return $raw;
77 | }
78 |
79 | public function artist($artist_id){
80 | $url='http://music.163.com/weapi/v1/artist/'.$artist_id.'?csrf_token=';
81 | $data=array(
82 | 'csrf_token'=>'',
83 | );
84 | $raw=$this->curl($url,$this->prepare($data));
85 | if($this->_MINI_MODE){
86 | $this->_MINI_MODE=false;
87 | $raw=json_decode($raw,1);
88 | return json_encode($this->clear_data($raw["hotSongs"]));
89 | }
90 | else return $raw;
91 | }
92 |
93 | public function album($album_id){
94 | $url='http://music.163.com/weapi/v1/album/'.$album_id.'?csrf_token=';
95 | $data=array(
96 | 'csrf_token'=>'',
97 | );
98 | $raw=$this->curl($url,$this->prepare($data));
99 | if($this->_MINI_MODE){
100 | $this->_MINI_MODE=false;
101 | $raw=json_decode($raw,1);
102 | return json_encode($this->clear_data($raw["songs"]));
103 | }
104 | else return $raw;
105 | }
106 |
107 | public function detail($song_id){
108 | $url='http://music.163.com/weapi/v3/song/detail?csrf_token=';
109 | $data=array(
110 | 'c'=>'['.json_encode(array('id'=>$song_id)).']',
111 | 'csrf_token'=>'',
112 | );
113 | $raw=$this->curl($url,$this->prepare($data));
114 | if($this->_MINI_MODE){
115 | $this->_MINI_MODE=false;
116 | $raw=json_decode($raw,1);
117 | return json_encode($this->clear_data($raw["songs"]));
118 | }
119 | else return $raw;
120 | }
121 |
122 | public function url($song_id,$br=999000){
123 | $url='http://music.163.com/weapi/song/enhance/player/url?csrf_token=';
124 | if(!is_array($song_id))$song_id=array($song_id);
125 | $data=array(
126 | 'ids'=>$song_id,
127 | 'br'=>$br,
128 | 'csrf_token'=>'',
129 | );
130 | return $this->curl($url,$this->prepare($data));
131 | }
132 |
133 | public function playlist($playlist_id){
134 | $url='http://music.163.com/weapi/v3/playlist/detail?csrf_token=';
135 | $data=array(
136 | 'id'=>$playlist_id,
137 | 'n'=>1000,
138 | 'csrf_token'=>'',
139 | );
140 | $raw=$this->curl($url,$this->prepare($data));
141 | if($this->_MINI_MODE){
142 | $this->_MINI_MODE=false;
143 | $raw=json_decode($raw,1);
144 | return json_encode($this->clear_data($raw["playlist"]["tracks"]));
145 | }
146 | else return $raw;
147 | }
148 |
149 | public function lyric($song_id){
150 | $url='http://music.163.com/weapi/song/lyric?csrf_token=';
151 | $data=array(
152 | 'id'=>$song_id,
153 | 'os'=>'pc',
154 | 'lv'=>-1,
155 | 'kv'=>-1,
156 | 'tv'=>-1,
157 | 'csrf_token'=>'',
158 | );
159 | return $this->curl($url,$this->prepare($data));
160 | }
161 |
162 | public function mv($mv_id){
163 | $url='http://music.163.com/weapi/mv/detail?csrf_token=';
164 | $data=array(
165 | 'id'=>$mv_id,
166 | 'csrf_token'=>'',
167 | );
168 | return $this->curl($url,$this->prepare($data));
169 | }
170 |
171 | protected function clear_data($result){
172 | // you can modify it by yourself, change to your API?!
173 | foreach($result as $key=>$vo){
174 | $data[$key]=array(
175 | 'id'=>$key,
176 | 'songid'=>$vo["id"],
177 | 'name'=>$vo["name"],
178 | 'cover'=>'https://p4.music.126.net/'.self::Id2Url($vo['al']["pic_str"]).'/'.$vo['al']["pic_str"].'.jpg',
179 | 'url'=>'http://music.163.com/song/media/outer/url?id='.$vo["id"],
180 | //'lyric'=>$vo["id"],
181 | 'artist'=>array(),
182 | );
183 | foreach($vo['ar'] as $vvo)$data[$key]['artist'][]=$vvo['name'];
184 | $data[$key]['artist']=implode('/',$data[$key]['artist']);
185 | }
186 | return $data;
187 | }
188 |
189 | public function mini(){
190 | $this->_MINI_MODE=true;
191 | return $this;
192 | }
193 |
194 | /* static url encrypt, use for pic*/
195 | public function Id2Url($id){
196 | $byte1[]=$this->Str2Arr('3go8&$8*3*3h0k(2)2');
197 | $byte2[]=$this->Str2Arr($id);
198 | $magic=$byte1[0];
199 | $song_id=$byte2[0];
200 | for($i=0;$iArr2Str($song_id),1));
202 | $result=str_replace('/','_',$result);
203 | $result=str_replace('+','-',$result);
204 | return $result;
205 | }
206 | protected function Str2Arr($string){
207 | $bytes=array();
208 | for($i=0;$iurl($id);
7 | $data=json_decode($result, true);
8 | return $data['data'][0]['url'];
9 | }
10 | function get_url_mv($id)
11 | {
12 | $api = new NeteaseMusicAPI();
13 | $result = $api->mv($id);
14 | $data=json_decode($result, true);
15 | $vurl = $data['data']['brs']['720'];
16 | if($vurl == null)
17 | {
18 | $vurl = $data['data']['brs']['480'];
19 | }
20 | return $vurl;
21 | }
22 | function get_lyric($id)
23 | {
24 | $api = new NeteaseMusicAPI();
25 | $result = $api->lyric($id);
26 | $data=json_decode($result, true);
27 | return $data['lrc']['lyric'];
28 | }
29 | function get_tlyric($id)
30 | {
31 | $api = new NeteaseMusicAPI();
32 | $result = $api->lyric($id);
33 | $data=json_decode($result, true);
34 | return $data['tlyric']['lyric'];
35 | }
36 | function get_playlist($id)
37 | {
38 | $api = new NeteaseMusicAPI();
39 | $result = $api->playlist($id);
40 | $data=json_decode($result, true);
41 | return $data['tlyric']['lyric'];
42 | }
43 |
44 | if(!empty($_GET['debug']))
45 | {
46 | if(!empty($_GET['id']))
47 | {
48 | $api = new NeteaseMusicAPI();
49 | $result = $api->url($_GET['id']);
50 | echo $result;
51 | }
52 | elseif(!empty($_GET['mv']))
53 | {
54 | $api = new NeteaseMusicAPI();
55 | $result = $api->mv($_GET['mv']);
56 | echo $result;
57 | }
58 | elseif(!empty($_GET['lyric']))
59 | {
60 | $api = new NeteaseMusicAPI();
61 | $result = $api->lyric($_GET['lyric']);
62 | echo $result;
63 | }
64 | elseif(!empty($_GET['tlyric']))
65 | {
66 | $api = new NeteaseMusicAPI();
67 | $result = $api->lyric($_GET['tlyric']);
68 | echo $result;
69 | }
70 | elseif(!empty($_GET['playlist']))
71 | {
72 | $api = new NeteaseMusicAPI();
73 | $result = $api->playlist($_GET['playlist']);
74 | echo $result;
75 | }
76 | }
77 | elseif(!empty($_GET['id']))
78 | {
79 | echo get_url_id($_GET['id']);
80 | }
81 | elseif(!empty($_GET['mv']))
82 | {
83 | echo get_url_mv($_GET['mv']);
84 | }
85 | elseif(!empty($_GET['lyric']))
86 | {
87 | echo get_lyric($_GET['lyric']);
88 | }
89 | elseif(!empty($_GET['tlyric']))
90 | {
91 | echo get_tlyric($_GET['tlyric']);
92 | }
93 | elseif(!empty($_GET['playlist']))
94 | {
95 | $api = new NeteaseMusicAPI();
96 | $result = $api->playlist($_GET['playlist']);
97 | echo $result;
98 | }
99 | else
100 | {
101 | echo 'nothing';
102 | }
103 | ?>
--------------------------------------------------------------------------------
/tools/video_convert_tool.py:
--------------------------------------------------------------------------------
1 | #coding:utf-8
2 | #电脑上用的视频渲染工具
3 | #用于夜间文件的预渲染工作
4 | #请自行用pip装好相应模块
5 | #还有个imageio.plugins.ffmpeg.download()记得运行
6 | #文件夹请自行更改
7 | #本工具仅用于生成ass字幕文件,渲染请去用小丸工具箱~
8 | import os
9 | import ass_maker
10 |
11 | path = 'C:\\Users\\liucx\\Desktop'
12 | #ffmpeg_path = 'C:\\Program Files (x86)\\MarukoToolbox\\tools\\ffmpeg.exe'
13 | maxbitrate = '1800'
14 | files = os.listdir(path+'\\downloads') #获取所有缓存文件
15 |
16 | for i in files:
17 | if i.find('.flv') != -1 or i.find('.mp4') != -1:
18 | print('find file:'+i)
19 | ass_maker.make_ass(i.replace('.flv','').replace('.mp4',''),'当前是晚间专属时间哦~时间范围:晚上22点-凌晨5点\\N大家晚安哦~做个好梦~\\N当前文件名:'+i,path)
20 | print('ffmpeg -i "'+path+'/downloads/'+i+'" -aspect 16:9 -vf "scale=1280:720, ass='+path+"/downloads/"+i.replace(".mp4",'').replace(".flv",'')+'.ass'+'" -c:v libx264 -preset ultrafast -maxrate '+maxbitrate+'k -tune fastdecode -acodec aac -b:a 192k "'+path+'/downloads/'+i+'rendering.flv"')
21 | #-threads 0
22 |
--------------------------------------------------------------------------------