You are on page 1of 6

12/14/2015

AudiovideoaddontutorialKodi

Audiovideoaddontutorial
FromKodi
(RedirectedfromAudio/Videoplugintutorial)
Development Addondevelopment Audiovideoaddontutorial
ThispagewilloutlinethebasicsofcreatingyourfirstPythonaddonforKodi.Itassumesyou'reatleast
familiarwiththebasicsofPython(oratleast,programmingingeneral).Ifnot,werecommendvisiting
thePythontutorial(http://docs.python.org/2/tutorial/)first,andthenreturninghere.

Contents
1Beforewegetstarted
2Hello,World!
3Navigatingbetweenpages
3.1Retrievingarguments
3.1.1Multiplecontenttypes
3.2Passingarguments
4Workingwithusersettings
5Showingadditionalmetadata
5.1Icons,thumbnailsandartwork
5.2Infolabels
5.3Streaminfo
6Addingcontextmenus

1Beforewegetstarted
Seealso:Addonstructure
Thefirststeptomakinganaddonistoputthebasicstructureinplace.Makesureyourdirectoryis
properlynamed,e.g.plugin.video.myaddon,andthatyouhaveaproperlyconstructedaddon.xmlfile.
Oncethesearedone,youcangetstartedwritingtheactualcodeforyouraddon!

2Hello,World!
ThesimplestformofPythonaddonisonethatgetsrun,addssomelistitems,andexitstoletKoditake
overthenavigationpeoplewhohavewrittenserversidecodeforthewebshouldbefamiliarwithhow
thisworks.(Morecomplexaddonscanprocessuserinputinrealtime,butwe'lldiscussthoselater.)
Let'sstartbylookingatanextremelybasicexamplescript:
importsys
importxbmcgui
importxbmcplugin
addon_handle=int(sys.argv[1])
http://kodi.wiki/view/Audio/Video_plugin_tutorial

1/6

12/14/2015

AudiovideoaddontutorialKodi

xbmcplugin.setContent(addon_handle,'movies')
url='http://localhost/some_video.mkv'
li=xbmcgui.ListItem('MyFirstVideo!',iconImage='DefaultVideo.png')
xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,listitem=li)
xbmcplugin.endOfDirectory(addon_handle)
Whilenotparticularlyexciting,thisshowstheminimalamountofcodeyouneedtogetanKodiaddon
upandrunninginPython.First,wegettheaddon'sprocesshandlefromsys.argv[1].Weneedthisto
tellKodiwhoweare.Next,wetellKodithatwe'regoingtoshowalistof'movies'.Thereareother
options,like'audio'or'episodes'thesejustchangesomedetailsofhowKodipresentsyouraddon.
Themostimportantpartisthatwecreateanxbmcgui.ListItemwiththenameandiconwewant
('DefaultVideo.png'comesfromtheKodiskin),setittobeavideoitem,andthenaddittothe
directory.Oncewe'redoneaddingitems,weneedtobesuretocallxbmcplugin.endOfDirectorytolet
Kodiknowwe'redone!

3Navigatingbetweenpages
Whilethefirstexamplemightbeenoughforextremelysimpleaddons,mostaddonswillwanttohave
theabilitytonavigatebetweendifferentpages.Mostaddonsaredesignedtoimitateafolderhierarchy
whereopeningfolderitemsshowsadifferentlistofitems,andgoing"up"returnsyoutotheparent
folder.

3.1Retrievingarguments
Aswesawinthefirstexample,Kodipassessomeargumentstousviasys.argv.Thisisimportant,since
it'swhatwillletustailortheoutputontheaddonbasedonuserinput.Remember,muchlikeawebsite,
eachfolder(orpage)inanKodiaddonistheresultofaseparateinvocationofourscript.The
argumentsavailabletousare:
Index

Description

ThebaseURLofyouraddon,e.g.'plugin://plugin.video.myaddon/'

Theprocesshandleforthisaddon,asanumericstring

Thequerystringpassedtoyouraddon,e.g.'?foo=bar&baz=quux'

Ofparticularinterestissys.argv[2],whichiswhatwe'llgenerallyusetoshowdifferentthingsinthe
addon.

3.1.1Multiplecontenttypes
Seealso:Addon.xml#<provides>element
Ifyouraddonprovidesmultiplecontenttypes,e.g.audioandvideo,whentheuserinvokesyouraddon
fromtheaddonlist,Kodiwilladdacontent_typeparametertoyouraddon'squerystring.Forexample:
'?content_type=audio'.Thiswillallowyoutomodifytheoutputdependingonwhatcontextyouradd
http://kodi.wiki/view/Audio/Video_plugin_tutorial

2/6

12/14/2015

AudiovideoaddontutorialKodi

onwasinvokedin.

3.2Passingarguments
Nowthatweknowhowtoretrievetheargumentspassedtoouraddon,we'llhavetoactuallypasssome
alongtoit.Generallyspeaking,thisinvolvescreatingafolderListItemwithaURLbacktoyouraddon
thenthenextinvocationoftheaddonwillparsethoseargumentsanddosomethingwiththem.Let's
lookatanotherbriefexamplethataddssomefolderstolettheusernavigatebetweendifferentpagesof
theaddon:
importsys
importurllib
importurlparse
importxbmcgui
importxbmcplugin
base_url=sys.argv[0]
addon_handle=int(sys.argv[1])
args=urlparse.parse_qs(sys.argv[2][1:])
xbmcplugin.setContent(addon_handle,'movies')
defbuild_url(query):
returnbase_url+'?'+urllib.urlencode(query)
mode=args.get('mode',None)
ifmodeisNone:
url=build_url({'mode':'folder','foldername':'FolderOne'})
li=xbmcgui.ListItem('FolderOne',iconImage='DefaultFolder.png')
xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,
listitem=li,isFolder=True)
url=build_url({'mode':'folder','foldername':'FolderTwo'})
li=xbmcgui.ListItem('FolderTwo',iconImage='DefaultFolder.png')
xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,
listitem=li,isFolder=True)
xbmcplugin.endOfDirectory(addon_handle)
elifmode[0]=='folder':
foldername=args['foldername'][0]
url='http://localhost/some_video.mkv'
li=xbmcgui.ListItem(foldername+'Video',
iconImage='DefaultVideo.png')
xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,
listitem=li)
xbmcplugin.endOfDirectory(addon_handle)

http://kodi.wiki/view/Audio/Video_plugin_tutorial

3/6

12/14/2015

AudiovideoaddontutorialKodi

Asyoucansee,manypartsofourcodeareverysimilartothefirstexample.Thereareafewimportant
additions,however.First,wewanttorespondtotheargumentssuppliedtoourscript,soweparsethe
querystringwith:
urlparse.parse_qs(sys.argv[2][1:])
Weskipthefirstcharacter,sinceit'salways'?'.Thiswillgiveusadictoflistsforexample,'?
foo=bar&foo=baz&quux=spam'wouldbeconvertedto{'foo':['bar','baz'],'quux':['spam']}.With
thisinformation,wecantailortheoutputofouraddontothesuppliedarguments.
Wealsoneedtobeabletocreatelinksbacktoouraddoninordertodisplayrelatedpages(e.g.
subfolders).Wecandothisbycreatinganxbmc.ListItem,passingisFolder=True,andsettingtheURL
oftheitemtopointbacktoouraddon.WecreatetheURLinthehelperfunctionbuild_url(),which
givesusaURLthatlookssomethinglike:
plugin://plugin.video.myaddon/?mode=folder&foldername=Folder+One

4Workingwithusersettings
Seealso:Addonsettings
Youraddonmayrequiresomeconfigurableoptionsfortheuser(e.g.logincredentialsforaservice).
Thesecanbestoredassettings.Tousesettingswithyouraddon,you'llneedtomakeafiledefiningthe
settingsinresources/settings.xml.Forexample:
<?xmlversion="1.0"encoding="utf8"standalone="yes"?>
<settings>
<settingid="my_setting"type="bool"default="true"label="My
Setting"/>
</settings>
Thiswillallowtheusertoopenthesettingsforyouraddonandmodifythissettingasneeded.Then,in
youraddon,youcanretrieveorsetthissettingwiththefollowingcode:
my_addon=xbmcaddon.Addon()
my_setting=my_addon.getSetting('my_setting')#returnsthestring
'true'or'false'
my_addon.setSetting('my_setting','false')

5Showingadditionalmetadata

http://kodi.wiki/view/Audio/Video_plugin_tutorial

4/6

12/14/2015

AudiovideoaddontutorialKodi

We'vealreadyseenhowtoshowsomebasicmetadata,liketheiconimageandthetypeoftheitem
('video'inourcase).However,therearemanymorepiecesofmetadatathatKodiunderstands,and
addingthemcanmakelifeeasieronyourusers.We'lltakealookatsomeofthemoreimportantones.
YoucanalsofindafulllistinthePythondocumentation(http://mirrors.kodi.tv/docs/pythondocs/)for
xbmcgui.ListItem(http://mirrors.kodi.tv/docs/pythondocs/16.xjarvis/xbmcgui.html#ListItem).

5.1Icons,thumbnailsandartwork
Ourpreviousexamplesalreadyshowedhowtosetanicon,butyoucanalsosetathumbnail,fanart(full
screenbackgroundimages)andotherartwork.TheycanbesetwiththeListItem.setArtmethod:
li=xbmcgui.ListItem(label='Myvideo')
li.setIconImage('icon.png')
li.setArt({'thumb':'thumbnail.jpg','poster':'poster.jpg''fanart':
'fanart.jpg'})
Note:InKodiIsengardandearlierthe'icon'typeisnotavailableforsetArt.Youmustuse
ListItem.setIconImage(...)

Ifyou'dprefertoshowthedefaultfanartfromyouraddon,youcangetthepathtothatimagefromthe
xbmcaddon.Addon(http://mirrors.kodi.tv/docs/pythondocs/16.xjarvis/xbmcaddon.html#Addon)

object:
my_addon=xbmcaddon.Addon('plugin.video.myaddon')
#...
li.setArt({'fanart':my_addon.getAddonInfo('fanart')})

5.2Infolabels
Kodialsoletsyouaddusefulinformationabouteachlistitem,likethecast,episodenumber,playcount,
andduration.Thespecificfieldsavailabledependonwhetheryourlistitemisvideo,audio,orapicture.
Inallcasesthough,theformatisroughlythesame.Forexample,toaddinfolabelstoamovie,you
mightdothefollowing:
info={
'genre':'Horror',
'year':1979,
'title':'Alien',
}
li.setInfo('video',info)
Forafulllistoftheavailableinfolabels,consultthedocumentationforListItem.setInfo
(http://mirrors.kodi.tv/docs/pythondocs/16.xjarvis/xbmcgui.html#ListItemsetInfo).

5.3Streaminfo
http://kodi.wiki/view/Audio/Video_plugin_tutorial

5/6

12/14/2015

AudiovideoaddontutorialKodi

Inadditiontometadataaboutthefile'scontents,youcanaddinformationabouttheaudio/videostreams
themselves.Foravideo,youmightdothefollowing:
video_info={
'codec':'h264',
'aspect':1.78,
'width':1280,
'height':720,
}
li.addStreamInfo('video',video_info)
li.addStreamInfo('audio',{'codec':'dts','language':'en','channels':
2})
li.addStreamInfo('subtitle',{'language':'en'})
Forcompletedocumentationaboutthisfunction,seeListItem.addStreamInfo
(http://mirrors.kodi.tv/docs/pythondocs/16.xjarvis/xbmcgui.html#ListItemaddStreamInfo).

6Addingcontextmenus
Inadditiontothedefaultactionforalistitem(e.g.playingthevideo),youraddoncanprovide
additionalactionsforaniteminthecontextmenu.Notethatthisonlyappliestolistitemsinyouradd
on.Currently,you'renotabletomodifythecontextmenuformoviesintheuser'slibrary.Toadda
contextmenuitem,youneedtogiveitalabelandabuiltinfunctionasastring:
li.addContextMenuItems([('Refresh','Container.Refresh'),
('Goup','Action(ParentDir)')])
Youcanalsoelecttoshowonlyyourcontextmenuitems:
li.addContextMenuItems([('Refresh','Container.Refresh')],
replaceItems=True)
Retrievedfrom"http://kodi.wiki/index.php?title=Audiovideo_addon_tutorial&oldid=102723"
Category: Addondevelopment
Thispagewaslastmodifiedon31October2015,at06:13.
Thispagehasbeenaccessed40,092times.
TextonthispageisavailableunderAttributionShareAlike3.0Unported.Imagesandvideomay
beunderadifferentcopyright.

http://kodi.wiki/view/Audio/Video_plugin_tutorial

6/6

You might also like