ОсновноеRadiotalkПользовательское
Технологии вещания, софт, скрипты
3   •   Посмотреть все темы

liquidsoap

 

6245
Тарас @tarasian666
Давно этот код не использовал, надо будет его перепроверить. Сейчас поьзуюсь скроблером на питоне, может и его выложу

20
Вадим @Vadim_CHichkan
Нашёл что-то подобное
**********
не работает(

6245
Тарас @tarasian666
у меня на основе этого **********

20
Вадим @Vadim_CHichkan
tarasian666 пишет:

у меня на основе этого **********

Не могу разобраться куда прописать логин и пароль
def connect(self, user, password, hashpw=False,
client=('tst', '1.0'), hs='true'):
"""
Connect to the url, with the user and the password.
The password can be hashed with the haslib :
hashlib.md5("pasword").hexdigest(), or a plain password and
hashpw to 'True'.
The client is a tuple : (client_id, client_version).
Do not touch hs.
For lastfm, more informations here :
**********
"""
self.user = user
self.client = client
if self.last_handshake:
next_allowed_hs = (self.last_handshake +
timedelta(seconds=self.hanshake_delay))
if datetime.now() < next_allowed_hs:
delta = next_allowed_hs - datetime.now()
raise ProtocolError(("Please wait another %d seconds until next"
" handshake (login) attempt.") % delta.seconds)

6245
Тарас @tarasian666
в самом низу скрипта, но там сразу какбы 2 скроблера, один можем убрать

20
Вадим @Vadim_CHichkan
вроде liquidsoap почти сьел этот скрипт, но снова ошибка
2014/08/25 23:32:48 [LastFM:3] Дискотека Авария - Труба Зовёт
2014/08/25 23:32:48 [stderr:3] Traceback (most recent call last):
2014/08/25 23:32:48 [stderr:3] File "/script/lastfm.py", line 356, in <module>
2014/08/25 23:32:48 [stderr:3] s in scrobblers]
2014/08/25 23:32:48 [stderr:3] TypeError: iteration over non-sequence

if __name__ == "__main__":
s = Scrobbler()
s.connect("cyrax1989", "ae9835248c1c41616ee6255c7eb9be7d")
scrobblers = (s)
print [s.now_playing('Front Line Assembly', 'Unleashed', length=317) for
s in scrobblers] #356
for s in scrobblers:
print s.submit('Front Line Assembly',
'Unleashed',
1192374052+(5*60),
source='P',
length=317
)
print s.flush()

Отредактировано Vadim_CHichkan - 26.08.2014
20
Вадим @Vadim_CHichkan
tarasian666 вы можете свой готовый скрипт сбросить для скроблинга с lastfm на питоне?? Если вы делали на основе этого ********** то значит что-то меняли (не только свой логин и пароль)
вопрос: возможно ли средствами liquidsoap обрезать песню, чтобы к примеру песня начиналась не с 0 секунды, а допустим, с 2-3 секунды или срезать концовку на несколько секунд??

Отредактировано Vadim_CHichkan - 27.08.2014
382
Grigorij @gyurgin_1
Vadim.CHichkan пишет:

tarasian666 вы можете свой готовый скрипт сбросить для скроблинга с lastfm на питоне?? Если вы делали на основе этого ********** то значит что-то меняли (не только свой логин и пароль)
вопрос: возможно ли средствами liquidsoap обрезать песню, чтобы к примеру песня начиналась не с 0 секунды, а допустим, с 2-3 секунды или срезать концовку на несколько секунд??

Элементарно - по аналогии с тем, что я вам показал для кроссфейда используя cue_cut, подробности выведет команда:
liquidsoap -h cue_cut .

Отредактировано gyurgin_1 - 27.08.2014
6245
Тарас @tarasian666

#!/usr/bin/python2
# -*- coding: utf-8 -*-
import sys
import urllib, urllib2
from time import mktime, time
from datetime import datetime, timedelta
from md5 import md5

SESSION_ID = None
POST_URL = None
NOW_URL = None
HARD_FAILS = 0
LAST_HS = None # Last handshake time
HS_DELAY = 0 # wait this many seconds until next handshake
SUBMIT_CACHE = []
MAX_CACHE = 5 # keep only this many songs in the cache
PROTOCOL_VERSION = '1.2'

class BackendError(Exception):
"Raised if the AS backend does something funny"
pass
class AuthError(Exception):
"Raised on authencitation errors"
pass
class PostError(Exception):
"Raised if something goes wrong when posting data to AS"
pass
class SessionError(Exception):
"Raised when problems with the session exist"
pass
class ProtocolError(Exception):
"Raised on general Protocol errors"
pass

def login( user, password, client=('tst', '1.0') ):
"""Authencitate with AS (The Handshake)

@param user: The username
@param password: The password
@param client: Client information (see ********** for more info)
@type client: Tuple: (client-id, client-version)"""
global LAST_HS, SESSION_ID, POST_URL, NOW_URL, HARD_FAILS, HS_DELAY, PROTOCOL_VERSION

if LAST_HS is not None:
next_allowed_hs = LAST_HS + timedelta(seconds=HS_DELAY)
if datetime.now() < next_allowed_hs:
delta = next_allowed_hs - datetime.now()
raise ProtocolError("""Please wait another %d seconds until next handshake
(login) attempt.""" % delta.seconds)

LAST_HS = datetime.now()

tstamp = int(mktime(datetime.now().timetuple()))
url = "http://post.audioscrobbler.com/"
pwhash = md5(password).hexdigest()
token = md5( "%s%d" % (pwhash, int(tstamp))).hexdigest()
values = {
'hs': 'true',
'p' : PROTOCOL_VERSION,
'c': client[0],
'v': client[1],
'u': user,
't': tstamp,
'a': token
}
data = urllib.urlencode(values)
req = urllib2.Request("%s?%s" % (url, data) )
response = urllib2.urlopen(req)
result = response.read()
lines = result.split('\n')


if lines[0] == 'BADAUTH':
raise AuthError('Bad username/password')

elif lines[0] == 'BANNED':
raise Exception('''This client-version was banned by Audioscrobbler. Please
contact the author of this module!''')

elif lines[0] == 'BADTIME':
raise ValueError('''Your system time is out of sync with Audioscrobbler.
Consider using an NTP-client to keep you system time in sync.''')

elif lines[0].startswith('FAILED'):
handle_hard_error()
raise BackendError("Authencitation with AS failed. Reason: %s" %
lines[0])

elif lines[0] == 'OK':
# wooooooohooooooo. We made it!
SESSION_ID = lines[1]
NOW_URL = lines[2]
POST_URL = lines[3]
HARD_FAILS = 0

else:
# some hard error
handle_hard_error()

def handle_hard_error():
"Handles hard errors."
global SESSION_ID, HARD_FAILS, HS_DELAY

if HS_DELAY == 0:
HS_DELAY = 60
elif HS_DELAY < 120*60:
HS_DELAY *= 2
if HS_DELAY > 120*60:
HS_DELAY = 120*60

HARD_FAILS += 1
if HARD_FAILS == 3:
SESSION_ID = None

def now_playing( artist, track, album="", length="", trackno="", mbid="" ):
"""Tells audioscrobbler what is currently running in your player. This won't
affect the user-profile on last.fm. To do submissions, use the "submit"
method

@param artist: The artist name
@param track: The track name
@param album: The album name
@param length: The song length in seconds
@param trackno: The track number
@param mbid: The MusicBrainz Track ID
@return: True on success, False on failure"""

global SESSION_ID, NOW_URL

if SESSION_ID is None:
raise AuthError("Please 'login()' first. (No session available)")

if POST_URL is None:
raise PostError("Unable to post data. Post URL was empty!")

if length != "" and type(length) != type(1):
raise TypeError("length should be of type int")

if trackno != "" and type(trackno) != type(1):
raise TypeError("trackno should be of type int")

values = {'s': SESSION_ID,
'a': unicode(artist).encode('utf-8'),
't': unicode(track).encode('utf-8'),
'b': unicode(album).encode('utf-8'),
'l': length,
'n': trackno,
'm': mbid }

data = urllib.urlencode(values)
req = urllib2.Request(NOW_URL, data)
response = urllib2.urlopen(req)
result = response.read()

if result.strip() == "OK":
return True
elif result.strip() == "BADSESSION" :
raise SessionError('Invalid session')
else:
return False

def submit(artist, track, time, source='P', rating="", length="", album="",
trackno="", mbid="", autoflush=False):
"""Append a song to the submission cache. Use 'flush()' to send the cache to
AS. You can also set "autoflush" to True.

From the Audioscrobbler protocol docs:
---------------------------------------------------------------------------

The client should monitor the user's interaction with the music playing
service to whatever extent the service allows. In order to qualify for
submission all of the following criteria must be met:

1. The track must be submitted once it has finished playing. Whether it has
finished playing naturally or has been manually stopped by the user is
irrelevant.
2. The track must have been played for a duration of at least 240 seconds or
half the track's total length, whichever comes first. Skipping or pausing
the track is irrelevant as long as the appropriate amount has been played.
3. The total playback time for the track must be more than 30 seconds. Do
not submit tracks shorter than this.
4. Unless the client has been specially configured, it should not attempt to
interpret filename information to obtain metadata instead of tags (ID3,
etc).

@param artist: Artist name
@param track: Track name
@param time: Time the track *started* playing in the UTC timezone (see
datetime.utcnow()).

Example: int(time.mktime(datetime.utcnow()))
@param source: Source of the track. One of:
'P': Chosen by the user
'R': Non-personalised broadcast (e.g. Shoutcast, BBC Radio 1)
'E': Personalised recommendation except Last.fm (e.g.
Pandora, Launchcast)
'L': Last.fm (any mode). In this case, the 5-digit Last.fm
recommendation key must be appended to this source ID to
prove the validity of the submission (for example,
"L1b48a").
'U': Source unknown
@param rating: The rating of the song. One of:
'L': Love (on any mode if the user has manually loved the
track)
'B': Ban (only if source=L)
'S': Skip (only if source=L)
'': Not applicable
@param length: The song length in seconds
@param album: The album name
@param trackno:The track number
@param mbid: MusicBrainz Track ID
@param autoflush: Automatically flush the cache to AS?
"""

global SUBMIT_CACHE, MAX_CACHE

source = source.upper()
rating = rating.upper()

if source == 'L' and (rating == 'B' or rating == 'S'):
raise ProtocolError("""You can only use rating 'B' or 'S' on source 'L'.
See the docs!""")

if source == 'P' and length == '':
raise ProtocolError("""Song length must be specified when using 'P' as
source!""")

if type(time) != type(1):
raise ValueError("""The time parameter must be of type int (unix
timestamp). Instead it was %s""" % time)

SUBMIT_CACHE.append(
{ 'a': artist,
't': track,
'i': time,
'o': source,
'r': rating,
'l': length,
'b': unicode(album).encode('utf-8'),
'n': trackno,
'm': mbid
}
)

if autoflush or len(SUBMIT_CACHE) >= MAX_CACHE:
flush()

def flush():
"Sends the cached songs to AS."
global SUBMIT_CACHE

values = {}

for i, item in enumerate(SUBMIT_CACHE):
for key in item:
values[key + "[%d]" % i] = item[key]

values['s'] = SESSION_ID

data = urllib.urlencode(values)
req = urllib2.Request(POST_URL, data)
response = urllib2.urlopen(req)
result = response.read()
lines = result.split('\n')

if lines[0] == "OK":
SUBMIT_CACHE = []
return True
elif lines[0] == "BADSESSION" :
raise SessionError('Invalid session')
elif lines[0].startswith('FAILED'):
handle_hard_error()
raise BackendError("Authencitation with AS failed. Reason: %s" %
lines[0])
else:
# some hard error
handle_hard_error()
return False


if __name__ == "__main__":
login( 'логин', 'пароль' )
submit(
str(sys.argv[1]),
str(sys.argv[2]),
int(time()),
source='P',
length=str(sys.argv[3])
)
print flush()




20
Вадим @Vadim_CHichkan
tarasian666 все работает спс

Отредактировано Vadim_CHichkan - 28.08.2014
20
Вадим @Vadim_CHichkan
gyurgin_1 вообщем получилось так
echo 'annotate:liq_cue_in=2.,liq_cue_out=212.:'. $res['url'];

обрезается начало на 2 секунды и трек длится 210 секунд, т.е. 3,5 минуты, возможно ли обрезать только начало и конец песни, не учитывая её длительность?

Отредактировано Vadim_CHichkan - 28.08.2014
382
Grigorij @gyurgin_1
Я только сейчас понял что Вам нужно - это проще было бы назвать - "отрезать от конца песни". А что мешает тупо посчитать? Берем ********** getid3, кидаем в папку со скриптом, в начале скрипта подключаем require_once 'getid3/getid3.php'; и потом дергаем длительность песни $ThisFileInfo = $getID3->analyze($res['url']);
getid3_lib::CopyTagsToComments($ThisFileInfo);
$duration = $ThisFileInfo['playtime_seconds'];

$duration и будет длительность - далее уже вычисляем что надо и т.д.
Да, и возможно придется окантовать $res['url'] при помощи realpath, ну это так - на всякий случай.

Отредактировано gyurgin_1 - 30.08.2014
22
Ярослав @EnigmA_MaN_1
Кто поможет настроить конфиг. требуется 5 разных плейлистов с одними и теми же джинглами и промо. - будут направлены на fallback-mount (icecast2) - а с программы на пк (radioboss) будет включаться прямой эфир. icecast уже настроил а вот с liquidsoap никак не получается - пробовал запускать первый конфиг в верху страницы. --- liquidsoap /home/radio/start_liquidsoap

#!/usr/bin/liquidsoap
set("log.file.path","/tmp/test.log")

pl = playlist("/home/ave/playlist.m3u")
output.icecast(%vorbis,
host = "-----------", port = 8000,
password = "---------", mount = "/rock-non.mp3",pl)

выдает:
Invalid value at line 4, char 14-39: That source is fallible.

31
Сергей @meloman197
Ребята, подскажите пожалуйста какого вида должен быть плейлист для Liquidsoap, будь то .pls или .m3u и какие пути в них прописывать для файлов? Необходимо чтобы треки читались в той же последовательности что и в файле плейлиста. Пробывал добавлять и .pls и .m3u плейлист, но ничего не добавляется. Заранее благодарен!

P.S. Если делать плейлист в формате .txt, то возможно только указание только полного пути к файлу одной строчкой для каждого трека?

Создаю файл playlist.txt:
/home/mscpliteusers/radio/autodj/MHR/Coney Hatch - She's Gone.mp3
/home/mscpliteusers/radio/autodj/Ballads/Cinderella - Nobody's Fool.mp3
/home/mscpliteusers/radio/autodj/Jingle/Jingle2.mp3
/home/mscpliteusers/radio/autodj/MHR/Jimi Jamison - Crossroads Moment.mp3
/home/mscpliteusers/radio/autodj/MHR/Scorpions - Big City Lights.mp3
/home/mscpliteusers/radio/autodj/MHR/Jean Beauvoir - Feel The Heat.mp3


Конфигурация liquidsoap:
#!/usr/bin/liquidsoap -d
set("init.daemon",true)
set("init.daemon.pidfile",false)
set("log.file.path","/var/log/liquidsoap/basic.log")
set("log.stdout",true)
set("log.level",3)
set("server.telnet.bind_addr","127.0.0.1")
set("server.telnet",true)
myplaylist = mksafe(playlist(reload=150, '/home/mscpliteusers/radio/playlist.txt'))
radio = myplaylist
radio = mksafe(radio)
radio = crossfade(start_next=6.0, fade_out=3.0, fade_in=3.0, radio)
output.icecast(%mp3(bitrate=192, id3v2 = true),
mount = "live.mp3", radio,
host = "localhost", port = 8000, password = "",

Но файлы проигрываются не в заданной последовательности, а в произвольной. В чем может быть проблема?

Отредактировано meloman197 - 11.09.2014
31
Сергей @meloman197
Подскажите пожалуйста, как в такой конфигурации сделать автообновление плейлиста (в данной конфигурации не срабатывает):
#!/usr/bin/liquidsoap -d
set("init.daemon",true)
set("init.daemon.pidfile",false)
set("log.file.path","/var/log/liquidsoap/basic.log")
set("log.stdout",true)
set("log.level",3)
set("server.telnet.bind_addr","127.0.0.1")
set("server.telnet",true)
myplaylist = playlist(mode='normal', reload=150, '/home/mscpliteusers/radio/playlist.txt')
radio = myplaylist
radio = mksafe(radio)
radio = crossfade(start_next=6.0, fade_out=3.0, fade_in=3.0, radio)
output.icecast(%mp3(bitrate=192, id3v2 = true),
mount = "live.mp3", radio,
host = "localhost", port = 8000, password = ""

Воспроизводит треки по порядку, но функция reload=150 не срабатывает. Заранее благодарен!

P.S. пробывал изменять строчку на такую: myplaylist = mksafe(playlist(mode='normal', reload=150, '/home/mscpliteusers/radio/playlist.txt')) но тоже не работает.

Отредактировано meloman197 - 11.09.2014
22
Ярослав @EnigmA_MaN_1
[h]срочно нужна помощь[/h]
#!/usr/bin/liquidsoap -d
set("init.daemon",true)
set("init.daemon.pidfile",false)
# Log dir
set("log.file.path","/tmp/classic-radio.log")

# Music
classic = playlist("/home/ave/music/classic/classic.m3u")
goro = playlist(reload = 600, "/home/ave/prog/goro/goro.m3u")
grand = playlist(reload = 600, "/home/ave/prog/grand/grand.m3u")
news = playlist(reload = 600, "/home/ave/prog/news/news.m3u")
putish = playlist(reload = 600, "/home/ave/prog/putish/putish.m3u")
kalend = playlist(reload = 600, "/home/ave/prog/kalend/kalend.m3u")
painter = playlist(reload = 600, "/home/ave/prog/painter/painter.m3u")
modbook = playlist(reload = 600, "/home/ave/prog/modbook/modbook.m3u")
kinoman = playlist(reload = 600, "/home/ave/prog/kinoman/kinoman.m3u")
sovet = playlist(reload = 600, "/home/ave/prog/sovet/sovet.m3u")

# Some jingles
jingles = playlist("/home/ave/music/jingles/jingles.m3u")


# If something goes wrong, we'll play this



classic_non = fallback([ request.queue(id="request"),
switch ([
({ (1w9h) or (3w9h) or (5w9h) or (1w11h30m) or (3w11h30m) or (5w11h30m)}, goro),

({ (1w9h30m) or (3w9h30m) or (5w9h30m) or (1w18h30m) or (3w18h30m) or (5w18h30m)}, grand),

({ (1w10h) or (3w10h) or (5w10h) or (1w13h) or (3w13h) or (5w13h) or (1w17h) or (3w17h) or (5w17h)}, news),

({ (1w10h30m) or (3w10h30m) or (5w10h30m) or (1w12h) or (3w12h) or (5w12h) or (1w16h30m) or (3w16h30m) or (5w16h30m)}, putish),

({ (1w11h) or (3w11h) or (5w11h) or (1w16h) or (3w16h) or (5w16h)}, kalend),

({ (1w12h30m) or (3w12h30m) or (5w12h30m) or (1w14h30m) or (3w14h30m) or (5w14h30m)}, painter),

({ (1w13h) or (3w13h) or (5w13h) or (1w17h30m) or (3w17h30m) or (5w17h30m)}, modbook),

({ (1w14h) or (3w14h) or (5w14h) or (1w19h) or (3w19h) or (5w19h)}, sovet),

({ (1w15h) or (3w15h) or (5w15h) or (1w18h) or (3w18h) or (5w18h)}, kinoman),

]), ])

# Now add some jingles
classic_non = random(weights=[1,5],[ jingles, classic ])
# And finally the security


# Stream it out
output.icecast (%mp3,
host = "*.*.*.*", port = *.*.*.*,
password = "*******", mount = "/classic-non.mp3",
classic_non)


при запуске выдает
At line 27, character 13: The variable classic_non defined here is not used
anywhere in its scope. Use ignore(...) instead of classic_non = ... if
you meant to not use it. Otherwise, this may be a typo or a sign that
your script does not do what you intend.

уже все перекопал ничего сделать не могу

888
Falcon @Falcon
Судя по всему вы объявили переменную
classic = playlist("/home/ave/music/classic/classic.m3u")
А дальше используете
classic_non = fallback(

22
Ярослав @EnigmA_MaN_1
Falcon пишет:

Судя по всему вы объявили переменную
classic = playlist("/home/ave/music/classic/classic.m3u")
А дальше используете
classic_non = fallback(

я писал и classic_non = classic и менял все на просто classic - безрезультатно

22
Ярослав @EnigmA_MaN_1
самое интересное что
#!/usr/bin/liquidsoap
set("init.daemon",true)
set("init.daemon.pidfile",false)
# Log dir
set("log.file.path","/tmp/basic-radio.log")

# Music
classic = playlist("/home/ave/music/classic/classic.m3u")
# Some jingles
jingles = playlist("/home/ave/music/jingles/jingles.m3u")
# If something goes wrong, we'll play this
security = single("/home/radio/sec/intro.mp3")

# Start building the feed with music
classic_non = classic
# Now add some jingles
classic_non = random(weights = [1, 4],[jingles, classic_non])
# And finally the security
classic_non = fallback(track_sensitive = false, [classic_non, security])

# Stream it out
output.icecast(%mp3,
host = "*,*,*,*,", port = 8000,
password = "*******", mount = "/classic-non.mp3",
classic_non)


работает прекрасно. но как добавил
classic_non = switch ([
({ (1w9h) or (3w9h) or (5w9h) or (1w11h30m) or (3w11h30m) or (5w11h30m)}, goro),

({ (1w9h30m) or (3w9h30m) or (5w9h30m) or (1w18h30m) or (3w18h30m) or (5w18h30m)}, grand),

({ (1w10h) or (3w10h) or (5w10h) or (1w13h) or (3w13h) or (5w13h) or (1w17h) or (3w17h) or (5w17h)}, news),

({ (1w10h30m) or (3w10h30m) or (5w10h30m) or (1w12h) or (3w12h) or (5w12h) or (1w16h30m) or (3w16h30m) or (5w16h30m)}, putish),

({ (1w11h) or (3w11h) or (5w11h) or (1w16h) or (3w16h) or (5w16h)}, kalend),

({ (1w12h30m) or (3w12h30m) or (5w12h30m) or (1w14h30m) or (3w14h30m) or (5w14h30m)}, painter),

({ (1w13h) or (3w13h) or (5w13h) or (1w17h30m) or (3w17h30m) or (5w17h30m)}, modbook),

({ (1w14h) or (3w14h) or (5w14h) or (1w19h) or (3w19h) or (5w19h)}, sovet),

({ (1w15h) or (3w15h) or (5w15h) or (1w18h) or (3w18h) or (5w18h)}, kinoman),

])
и goro = playlist("/home/ave/prog/goro/goro.m3u")
grand = playlist("/home/ave/prog/grand/grand.m3u")
news = playlist("/home/ave/prog/news/news.m3u")
putish = playlist("/home/ave/prog/putish/putish.m3u")
kalend = playlist("/home/ave/prog/kalend/kalend.m3u")
painter = playlist("/home/ave/prog/painter/painter.m3u")
modbook = playlist("/home/ave/prog/modbook/modbook.m3u")
kinoman = playlist("/home/ave/prog/kinoman/kinoman.m3u")
sovet = playlist("/home/ave/prog/sovet/sovet.m3u")

стало выдавать эту фигню. The variable classic_non defined here is not used
anywhere in its scope. Use ignore(...) instead of classic_non = ... if
you meant to not use it. Otherwise, this may be a typo or a sign that
your script does not do what you intend.

6245
Тарас @tarasian666
последнюю запятую убрать не пробовали?