getmusicbee.com

Support => Developers' Area => MusicBee API => Topic started by: Steven on September 27, 2010, 08:57:49 PM

Title: MusicBee API
Post by: Steven on September 27, 2010, 08:57:49 PM
I've created the first version of an API that enables plugin developers to access information held in MusicBee and to control MusicBee.
Initially the API is focussed on enabling your plugin to be notified of player events, retrieve tag data, and to control the player. Over time I will add APIs to stream music data, control GUI aspects so you can create new views or possibly entirely skin MusicBee.

I would appreciate anyone building a plugin to let me know so I know whats coming down the line so I dont end up duplicating anything, or so I can prioritise adding new API calls.

Get the latest MusicBee beta from the downloads topic
http://getmusicbee.com/forum/index.php?board=6.0

All dlls need to be named MB_*.dll and placed in the Plugins folder where MB is installed.
If using C# or VB.NET, you need to target .NET 4.0 client profile and for all interfaces note that MusicBee runs in 32-bit mode on 64-bit machines

API interface and examples for v2.5:
C# source
http://www.mediafire.com/download/68vyibca4d80a7p/C#_Source.zip
VB.NET source
http://www.mediafire.com/download/2b7xx3orh0c9x07/VB_Source.zip
C++ source - this is no longer being updated with new API methods - contact me if you would need to use the C++ API
http://www.mediafire.com/?i53gtmmoq41rsac

API interface and examples for v3.0:
C# source
http://www.mediafire.com/download/5x2s51afgiq9y3i/C#_Source3.0.zip
VB.NET source
http://www.mediafire.com/download/acgyipk8f8z8jhh/VB_Source3.0.zip


API interface and examples for v3.1+:
C# source
http://www.mediafire.com/file/1cio56q16btp5p7/C%23_Source3.1.zip
VB.NET source
http://www.mediafire.com/file/v9207ekc5h8xojx/VB_Source3.1.zip
C++ source - this API is very old and missing many new API methods - contact me if you would need to use the C++ API
http://www.mediafire.com/?i53gtmmoq41rsac

The API interface is backwards compatible, so you are not required to update your plugin every time the API is updated
Title: Re: MusicBee API
Post by: Steven on September 29, 2010, 10:26:21 PM
i've also created a .NET interface with C# and VB.NET code samples. See the first post for links

For the C++ interface, I needed to change the Initialise function to take the musicbee api as a pointer, so please get the latest source code, replace MusicBeeInterface_1_0.h, and edit the Initialise function:
PluginInfo* Initialise(MusicBeeApiInterface* apiInterface)

You will also need the updated MusicBee.exe

I created 2 new API calls:
- NowPlaying_GetFileProperty(FilePropertyType type)
- NowPlaying_GetFileTag(MetaDataType type)

which differ from the Library_ API in that the files dont need to be in the library eg. the current playing track from a radio stream

Going forward, any new API calls will be versioned and wont require you to update your plugin
Title: Re: MusicBee API
Post by: Steven on October 11, 2010, 06:10:57 PM
The latest 1.2 beta on the downloads topic now supports artwork and lyric plugins.
Also supports an additional notification type enumeration
            PluginStartup = 0,          // notification sent after successful initialisation for an enabled plugin

Title: Re: MusicBee API
Post by: Londinium on October 14, 2010, 08:52:26 PM
I have no time to check that right now but as it's relative to my interests, I add it to my TODO ;-)
Title: Re: MusicBee API
Post by: thegreyspot on October 17, 2010, 06:20:30 PM
Would you be ok if I copy this to the wiki?
Title: Re: MusicBee API
Post by: Steven on October 17, 2010, 06:59:28 PM
yes thats fine
Title: Re: MusicBee API
Post by: stas on October 24, 2010, 04:30:51 PM
I totally like the idea of making API.

What about me, the only thing I want to do with the API - to create my own simplififed skin for listening with ability of switching to the full skin (MusicBee has a lot of functions, but many of them are not for everyday use).
The problem is the entry level. Markup languages like xml are enough for creating skins and also much simplier than C++ or VB. So I hope that knowledge of xml would be enough for making skins.
Title: Re: MusicBee API
Post by: ferongr on October 24, 2010, 07:00:42 PM
I totally like the idea of making API.

What about me, the only thing I want to do with the API - to create my own simplififed skin for listening with ability of switching to the full skin (MusicBee has a lot of functions, but many of them are not for everyday use).
The problem is the entry level. Markup languages like xml are enough for creating skins and also much simplier than C++ or VB. So I hope that knowledge of xml would be enough for making skins.

Lookup "API on Wikipedia. In short, an API allows third party applications to interchange data and interact with Musicbee. A skin... is just a skin. Normally, it doesn't change how the application works. While due to a lack of time I haven't gone through the API, if it's complete it could be easy to whip out a simple GUI that does basic operations (I don't know about library querying). But then, you could just use mini mode.

Some people are into sidebar apps or "Gadgets" for controlling their music applications, but personally I think they're unnecessary and not a "correct" way to control a music app in the background, since you normally have windows tiled or maximized over them.
Title: Re: MusicBee API
Post by: Steven on October 24, 2010, 10:41:49 PM
the skins are already implemented as XML. However both the skin XML and also the MusicBee API are quite basic at the moment eg. the skin XML has very few positioning and sizing attributes. Over time, probably more so next year I will add to them both.
But with the API in particular if anyone wants to achieve some sort of plugin with it and it is missing the required API calls let me know and I will give priority to it.
Title: Re: MusicBee API
Post by: stas on October 25, 2010, 08:54:44 AM
Yes, I miss positioning and sizing abilities.
Ideally xml-skinning should looks like this http://dev.winamp.com/wiki/Modern_Skin:_Intro
Title: Re: MusicBee API
Post by: Londinium on November 11, 2010, 02:03:44 PM
Hello,

Is there any way via the actual API methods to read through the library?
I guess the database is in SQLite 3 and it would be great if we could access it via SQL commands!
Title: Re: MusicBee API
Post by: Steven on November 11, 2010, 02:39:56 PM
yes there is - i dont have the api's in front of me right now but its something like:
if musicbeeApi.Library_Query(query)
- this initiates the query - for now just pass null as the query but when the parameter is supported it will be the same query xml as auto-playlists
  repeat
     url = musicbeeApi.Library_QueryGetNext()
     if url is null then exit loop
     artist = musicbeeApi.Library_GetFileMetadata(url, artist field code)  - the supported fields codes are defined in an enumeration
     title = musicbeeApi.Library_GetFileMetadata(url, title field code)
     ...
  loop
end

you can see each api signature in the MusicBeeInterface file in the examples zip
Title: Re: MusicBee API
Post by: Londinium on November 11, 2010, 03:03:49 PM
Thank you, I'll try that :)
Title: Re: MusicBee API
Post by: thegreyspot on February 08, 2011, 03:39:01 PM
Is there anyway to integrate the musicbee api with java?
Title: Re: MusicBee API
Post by: Steven on February 08, 2011, 10:14:01 PM
no there isnt any java interface and I dont know how to interface between java and .NET.
Visual Studio a great development platform and C# is nice language, also useful in the corporate job market if you are interested to learn.
Title: Re: MusicBee API
Post by: thegreyspot on February 08, 2011, 10:48:34 PM
Ok fair enough.Java is just what i learnt in school and is what the Android OS uses :(
Title: Re: MusicBee API
Post by: carloscs on February 09, 2011, 02:48:57 AM
If you really, really, really  want to you can look into IKVM (http://www.ikvm.net/).

But I would just do it  with visual studio, much simpler, and c# has many similarities to java, so it should be easy to get into.

Title: Re: MusicBee API
Post by: gavin19 on March 07, 2011, 08:40:48 PM
Thanks for the API and the example (huge help). I only know a tiny bit of VB but I was able to make myself a plugin to save a list of played tracks to a log file. Not exactly earth shattering in it's scope, but it's of use to me. Cheers :)
Title: Re: MusicBee API
Post by: kelsos on March 16, 2011, 07:18:59 PM
I was checking about a configuration panel for a plugin I am working, and I found this "not implemented yet: height in pixels that musicbee should reserve in a panel for config settings. When set, a handle to an empty panel will be passed to the Configure function" is it still not implemented?
Title: Re: MusicBee API
Post by: Steven on March 16, 2011, 08:00:47 PM
i forgot about that. I will do it this weekend
Title: Re: MusicBee API
Post by: Steven on March 19, 2011, 05:45:04 PM
this is a new MusicBee.exe that supports the in-built panel for entering config settings. It will be in the next weekly update as well
http://www.mediafire.com/?a7ymkpdn944vtcs

One thing to be aware, the Configure command can be called more than once during a MB session. When (if) that happens, a handle to a new empty panel is passed so the panel needs to be populated from scratch

C#:
using System.Drawing;
using System.Windows.Forms;

public bool Configure(IntPtr panelHandle)
{
   // save any persistent settings in a sub-folder of this path
   string dataPath = mbApiInterface.Setting_GetPersistentStoragePath();
   // panelHandle will only be set if you set about.ConfigurationPanelHeight to a non-zero value
   // keep in mind the panel width is scaled according to the font the user has selected
   if (panelHandle != IntPtr.Zero) {
      Panel configPanel = (Panel)Panel.FromHandle(panelHandle);
      Label prompt = new Label();
      prompt.AutoSize = true;
      prompt.Location = new Point(0, 0);
      prompt.Text = "prompt:";
      TextBox textBox = new TextBox();
      textBox.Bounds = new Rectangle(60, 0, 100, textBox.Height);
      textBox.TextChanged += textBox_TextChanged;
      configPanel.Controls.AddRange(new Control[] {prompt,textBox   });
   }
   return true;
}

private void textBox_TextChanged(object sender, EventArgs e)
{
   // save the value
}

VB:
Imports System.Drawing
Imports System.Windows.Forms

    Public Function Configure(ByVal panelHandle As IntPtr) As Boolean
        ' panelHandle will only be set if you set about.ConfigurationPanelHeight to a non-zero value
        ' keep in mind the panel width is scaled according to the font the user has selected
        If panelHandle <> IntPtr.Zero Then
            Dim configPanel As Panel = Panel.FromHandle(panelHandle)
            Dim prompt As New Label
            prompt.AutoSize = True
            prompt.Location = New Point(0, 0)
            prompt.Text = "prompt:"
            Dim textBox As New TextBox
            textBox.Bounds = New Rectangle(60, 0, 100, textBox.Height)
            AddHandler textBox.TextChanged, AddressOf textBox_TextChanged
            configPanel.Controls.AddRange(New Control() {prompt, textBox})
        End If
        Return True
    End Function

    Private Sub textBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        ' save the value
    End Sub
Title: Re: MusicBee API
Post by: Steven on March 21, 2011, 11:14:41 PM
from MB v1.2.4097+
Changes to the API - you need to get the latest MusicBeeInterface file from the example liinks below (however it should be backwards compatible so no need to rebuild an already released dll unless you are doing a lyrics or artwork plugin)

Lyrics and Artwork
for lyrics and artwork plugins, the following function needs to return an array of names of providers that your plugin supports

public string[] GetProviders()

the interface for RetrieveLyrics and RetrieveArtwork now includes a parameter for the provider you should return lyrics or artwork from - the idea being MB will iterate through the providers one by one in the order specified in MB Tags(2) preferences

public string RetrieveLyrics(string sourceFileUrl, string artist, string trackTitle, string album, bool synchronisedPreferred, string provider)
public string RetrieveArtwork(string sourceFileUrl, string albumArtist, string album, string provider)


Updating file tags
Library_SetFileTag(sourceFileUrl, type, value) now updates a "pending changes" cache rather than directly updating the internal MB library cache. This is so you cant end up with the cache being out-of-synch with tags in the files
Library_CommitTagsToFile(sourceFileUrl) updates the music file as before
MB_RefreshPanels() is a new function that should be called when you have finished updating the files (if updating many files its not a good idea to call as each file is updated as it will slow things down a lot)

new function returns the window handle for MB:
IntPtr handle = mbApiInterface.MB_GetWindowHandle();

updated examples
C++
http://www.mediafire.com/?mmt2p0vv5f26ty2
C#
http://www.mediafire.com/?ezf48kdce1yakci
VB
http://www.mediafire.com/?fr5msmdbxixtbrb
Title: Re: MusicBee API
Post by: kelsos on April 04, 2011, 05:22:31 PM
May I ask, the controls used in the application are custom? I am currently working on a Now Playing plugin for Skype, easy enough but I have some issues with the look an feel of the controls (button and checkbox specifically) in the settings panel. Any suggestions on what should I search/read in order to achieve a similar optical outcome, so that they 'll look like similar to the other controls?
Title: Re: MusicBee API
Post by: Steven on April 04, 2011, 06:40:13 PM
there is an exposed function
Setting_GetSkinElementColour
that returns the colours used for the skin the user has selected (its quite limited though in what elements you can get the values for)
but anyway, as i have done some of the controls myself such as the radio box and buttons, it might be better if expose an api call so that MB creates a control and returns the handle to it so you can add to your panel. I might not be able to look at it for some time though
Title: Re: MusicBee API
Post by: kelsos on April 04, 2011, 10:42:21 PM
Yeah I already use that, but still some controls look like they are out of place. Though the idea of the future API call is nice, it could make it easier for the developers to make settings menu that looks like the rest of the application. Anyway at the moment I should probably look on how to make some custom controls that look at least similar to the rest. I am already working (or at least trying too) on a custom button. It would be a nice experience.
Title: Re: MusicBee API
Post by: Maleko12 on April 30, 2011, 07:14:28 PM
how is the skype plugin working out?
Title: Re: MusicBee API
Post by: Elberet on June 01, 2011, 01:20:47 PM
While you're looking at letting MB create custom-styled controls, would it be possible to add an API call to get the fonts and font sizes used throughout MB? (Especially for buttons...)
Title: Re: MusicBee API
Post by: Steven on June 01, 2011, 02:01:18 PM
i wont be doing this for some time, but for the fonts just get that from the panel handle thats passed to the Configure function eg. Panel.FromHandle(panelHandle).Font
I'll just mention i will be updating the API for the next update to support Storage and Streaming handling (to handle Media Servers) and one of the changes will also be to allow exposing a SaveSettings function. So you wont need your button for that anymore.
Title: Re: MusicBee API
Post by: Steven on June 05, 2011, 10:15:00 PM
added the following (see the updated examples file in the first post)
- new API for:
  SaveSettings()
  called by MusicBee when the user clicks "Apply" or "Save" in the preferences screen. Its up to your plugin to figure out if the settings have changed and need to be saved

- several API methods to support retrieval and stream of files on a server. Its probably best to contact me if you want to add support for a media server
Title: Re: MusicBee API
Post by: Elberet on June 06, 2011, 05:43:49 PM
However, there are different fonts for buttons and labels -- at least the font size on MusicBee's own buttons is noticeably smaller then the font size used for most labels.

Do you have any guidelines on how large a plugins' configuration panel may get? Would modal dialog windows be acceptable?
Title: Re: MusicBee API
Post by: boroda on June 22, 2011, 09:59:12 PM
Steven, could you add a few options to API:

1. function to query for all selected files in current view.
2. possibility for plugins to add main menu items (i suggest that clicking on this items should send custom notifications to plugin).
Title: Re: MusicBee API
Post by: Steven on June 22, 2011, 10:03:36 PM
for 1, thats fine
for 2, can you give a specific example you have in mind
Title: Re: MusicBee API
Post by: boroda on June 22, 2011, 10:17:05 PM
for 2, can you give a specific example you have in mind
I try to develop small plugin for coping one tag to another and for swapping 2 tags for selected files. Suppose that the only sense to use such plugin is to invoke its functions from menu/hotkey/toolbar button (mostly important is menu).  

3. Would it be possible to get user defined names (ie displayed names) for custom tags?
Title: Re: MusicBee API
Post by: Elberet on June 23, 2011, 02:35:40 AM
With regard to this...
http://getmusicbee.com/forum/index.php?action=post;topic=3778.0;num_replies=2

This took me a bit by surprise... I, too, assumed that a plugin would get a TagsChanged notification whenever a file in the library had its tags altered...

I'm probably just too blind, but is there a complete documentation for the API somewhere? Such as what gets fired when, what the more obscure API calls actually do, and so on?
Title: Re: MusicBee API
Post by: boroda on June 23, 2011, 12:18:27 PM
I'm probably just too blind, but is there a complete documentation for the API somewhere? Such as what gets fired when, what the more obscure API calls actually do, and so on?
Download code examples at the beginning of this topic. Examples contain MusicBeeInterface.cs (and for other languages too) with full API, but its mostly self-documenting (using meaningful names) and almost without comments.
Title: Re: MusicBee API
Post by: boroda on June 25, 2011, 03:02:25 PM
Steven, 2 more (related to previous) requests for MB API:

1. Could you add function to query for all displayed files in current view. Of course I mean files included in currently displayed track list, not the files that are physically displayed on monitor (this may be useful if no files are selected and for plugins that do not modify files - i.e. exports some info about currently displayed tracks).

2. Could you add function to get localized tag names and file properties  (such as 'Play Count, 'Play Skip', etc.) along with function to get user defined names of custom tags?
Title: Re: MusicBee API
Post by: Steven on June 25, 2011, 03:05:39 PM
i should be starting on the next MB version next weekend so i will look at these requests then
Title: Re: MusicBee API
Post by: Elberet on June 28, 2011, 10:29:30 AM
Download code examples at the beginning of this topic.
Examples are great, but this is not what I'd call documentation... besides, it should be kinda obvious that I've looked at these files before, no? :-)
Title: Re: MusicBee API
Post by: e-motiv on June 29, 2011, 01:16:38 PM
Is there any way the API or functions of musicbee directly can be called via COM or Dll Call or Windows PostMessage?

DLL: I checked all dll's and exe's in the musicbee folder with DLL Export viewer, but got nothing, though don't know if that is the way to be certain.
COM: Also, since people talke about .NET and I thought that .NET can always be accessed via COM, maybe that route is also a way?
Windows Postmessage: No idea where this takes effect in MB...

This has all to do with the fact that I want to do small stuff in Musicbee via Autohotkey (autohotkey.net).
(e.g. http://getmusicbee.com/forum/index.php?topic=3778.msg20512)

Now, if everything here fails, and I have to take the road of C#, I wonder:
- Is the development wiki still and forever down?
- Can anyone set me on my way with eclipse (C#)? (I have downloaded the C# file from the first post and though I work with classes a lot in other environments I am totally confused what file/class is used for what end and how to begin with even a simple "Hello World", even a simple C compiled "anything".   ::)

Thanks and don't forget, holding my hand might give the community an extra plugin developer.   ;D :P
Title: Re: MusicBee API
Post by: Elberet on June 29, 2011, 01:39:56 PM
I noticed there's no API to add items to the now playing list other than play now (which replaces everything with the selected file), queue next (which inserts the file after the currently playing item but appears to be broken) and queue last (which I haven't tested yet). I'm not sure how useful this would be, and I don't have an application for this missing API myself, right now... but anyways, a few APIs to remove and insert now-playing list items by index, get the total count of now-playing items, get the index of the currently playing item and get the indices of selected items would be nice to complete the interface.


@R U Bn: As far as I know, MusicBee does not expose any COM interfaces, and I'm not aware that it's even possible to handle direct Post messages in C# (Windows' window messages are handled deep inside the Windows Forms library)...

Personally, I have the luxury of a free Visual Studio 2010 (Pro even) via the MSDNAA program, so I can't help you with setting up things in Eclipse, but if you have any concrete questions about how MusicBee interacts with your plugin DLL, I might be able to give you some pointers. (Basically, MB loads your DLL and invokes a few methods with well-known names, such as MusicBeePlugin.Plugin#Initialize. Any communication from MB to the plugin happens by MB calling these methods, and any communication from the plugin to MB happens by the plugin calling one of a bunch of delegates it received from MB via the Initialize method (if you know C, delegates are type-safe and nicely encapsulated function pointers slash trampolines). As such, MusicBee plugins are quite specialized, as far as Hello-World-type .NET programs go...)
Title: Thanks, Elebert and more help appreciated from other people!
Post by: e-motiv on June 29, 2011, 03:15:44 PM
Thank you, Elberet!  Very useful!
Though the interaction explanation doesn't enable me to start programming, the distinction between "from and to" MB etc. wíll be very useful once started.  Simple really, but only once you know it.  :-)

About post messages:
I'm not aware that it's even possible to handle direct Post messages in C# (Windows' window messages are handled deep inside the Windows Forms library)...
Do you mean from my (autohotkey) side?  Since they do make it possible to send post messages to any process or window. (Dunno if they used C# or not.)
Or do you mean from MB's side (receiving them)?  Then, I guess, it's probably out of the question unles it has been explicitly built in, or?

Anybody else that can ..
1. ..complete Elberet's info, like "dll call" (or further his info around post messages, see above)?  (COM is out apparently :-(  :-) )
2. ..set me on my way with eclipse?

Thanks again..
Title: Re: MusicBee API
Post by: Elberet on June 29, 2011, 05:18:41 PM
I was talking about MusicBee's side... Essentially, when there are any events for a window - mouse movement, key presses, you name it -, they are put into a queue. The program typically contains a loop that calls the Windows API to take an event from that queue and send it to the window's WindowProc. "Posting" a message to a window means that you put a user-defined event into that queue; eventually, the window's WindowProc will be called with that event, and if it knows how to process it, stuff happens... or it will just silently ignore your message.

Regarding Eclipse... maybe these help:
http://emonic.sourceforge.net/html/usage.html - Emonic is a C#/.NET 2.0 plugin for Eclipse, the link explains how it's set up.
http://monodevelop.com/ - Not based on Eclipse. Mono is the opensource implementation of C#/.NET, so this should work just as well with the "real" .NET CLR.
Visual Studio 2010 Express (http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express) - a free version of Visual Studio. It's a bit crippled (lacks certain refactoring features, you can't manually attach the debugger to random processes, etc.), but otherwise unlimited (no restriction on code size, all .NET features available, and no limitations on how you can license or sell your code/program).

Btw:
MusicBeeInterface.cs contains all the definitions and constants used by MusicBee. (All these enums, delegates and structs are members of the MusicBeePlugin.Plugin class.)
TestCSharpDll.cs contains the rest of the class MusicBeePlugin.Plugin, notably the various well-known methods called by MusicBee to communicate with your plugin, as well as a bit of example code that illustrates how messages are sent to MusicBee and how MusicBee's notifications are handled.
Properties\AssemblyInfo.cs is auto-generated (and auto-modified) by Visual Studio and contains a bunch of attributes that define the product name, description, copyright, version etc. strings embedded into the DLL file.
Title: Re: MusicBee API
Post by: Steven on June 29, 2011, 09:20:01 PM
API is updated with 2 new functions to support the boroda74's tag tools plugin
            public MB_AddMenuItem(string menuPath, string hotkeyDescription, EventHandler handler);
            public Setting_GetFieldName(MetaDataType type);

but MB_AddMenuItem will only work for boroda74 - i will notify when it have made it generally handle adding menus anywhere in MB

updated musicbee.exe (or get latest weekly update when this link is dead)
http://www.mediafire.com/?moxi4503us5w4tc


Is there any way the API or functions of musicbee directly can be called via COM or Dll Call or Windows PostMessage?
for a working open source plugin example see
https://code.google.com/p/mbprocessbar/
Title: Re: MusicBee API
Post by: Elberet on June 30, 2011, 02:11:10 AM
Another thing: you mentioned that Library_GetFileProperty only works on files in the library, but NowPlaying_GetFileProperty works on the currently playing file regardless whether it's in the library or not. So for any other files in the Now Playing list that aren't yet in the library, it's not possible to get the properties?
Title: Re: MusicBee API
Post by: Steven on June 30, 2011, 06:22:24 AM
you can get non-library files using:
NowPlaying_GetFileTag
NowPlayingList_QueryFiles then calling Library_GetFileTag
Playlist_QueryFiles then calling Library_GetFileTag
however i see i put a block on Library_GetFileTag which i have just removed, so for the next update it should work
Title: Re: MusicBee API
Post by: e-motiv on June 30, 2011, 08:42:05 PM
http://emonic.sourceforge.net/html/usage.html - Emonic is a C#/.NET 2.0 plugin for Eclipse, the link explains how it's set up.
Finally, after many hours, I got it to work and the (example) plugin works in MB! Eureka!

For possible future users of Emonic (Eclipse):
* U have to install NAnt yourself and set the path in Global preferences (.NET, Building, Nant).
* The "Emonic Auto Builder" never works more than once for me, try making your own builder with the same NAnt path (Project properties, builders, new).
edit: it actually does work, I just didn't know you have to "Clean" your project first (after failures?)
* Sometimes some .build file editing helps overcome some otherwise hidden problems...
Title: Re: MusicBee API
Post by: e-motiv on June 30, 2011, 09:40:39 PM
Where can I put a little html file I put together for starting plugin developers? (Based on Elberet's info)
Title: Re: MusicBee API
Post by: Steven on June 30, 2011, 09:53:24 PM
could you set up a topic in the "How To" section?
Title: Re: MusicBee API
Post by: e-motiv on June 30, 2011, 10:03:21 PM
Sure, but how do I write html on this forum? I'd prefer not to do everything in html and BBcode
Title: Re: MusicBee API
Post by: Steven on June 30, 2011, 10:15:22 PM
i could host the html page on this website if you want, but it might be better to put it somewhere you can control (eg. dropbox) if you need to edit it
Title: Re: MusicBee API
Post by: e-motiv on July 03, 2011, 08:00:33 PM
Sure, but how do I write html on this forum? I'd prefer not to do everything in html and BBcode
API Docs, HowTo's etc.. (http://getmusicbee.com/forum/index.php?topic=3864.0) <- Like this OK?
Title: Re: MusicBee API
Post by: Elberet on July 04, 2011, 11:17:39 AM
By the way... in my eternal quest for elegant code (it's a curse, really), I've encapsulated the raw MusicBee API in a nicer, more .NET'ish set of classes with Properties and Events -- fancy stuff. Basically, the idea is that I hate (with a vengeance) longwinded switch-case constructs and rather wanted something like...
Code
api.TrackChanged += (MusicBeeEventArgs args) => { Console.WriteLine(args.RelatedFile.AlbumArtist); };
then...
Code
public void ReceiveNotification(string sourceFileUrl, NotificationType type) {
    switch(type) {
        case NotificationType.TrackChanged:
            Console.WriteLine(mbApiInterface.Library_GetFileTag(relatedFile, MetaDataType.AlbumArtist);
            break;
    }
}

Would something like this make life easier for you, R U Bn?
Title: Re: MusicBee API
Post by: e-motiv on July 04, 2011, 12:51:30 PM
Would something like this make life easier for you, R U Bn?
It would! Great!  Reminds me of AS 3 (which follows the ECMA standard).  More developer-friendly.
Title: Re: MusicBee API
Post by: Elberet on July 04, 2011, 03:13:02 PM
Right. I'll clean this up and put a preview version on GitHub or something.

---

Now to something completely different (not!): NowPlaying_GetDuration returns the current playback duration as an integer number of milliseconds. Library_GetFileProperty and NowPlaying_GetFileProperty when called with FilePropertyTag.Duration return a less precise formatted string. This is weird, and I'd prefer milliseconds in all three cases. :-/
Title: Re: MusicBee API
Post by: Elberet on July 06, 2011, 02:03:30 AM
I've pushed my plugin API wrapper to github: https://github.com/Elberet/MusicBeeAPI

You can either fork the repository with any implementation of Git or download an archive. Some highlights:
Example: listen to TrackChanged events and print the changed-to track's title on the console. (Not terribly useful since there is no console, but the code works.)
Code
using System;
using System.Windows.Forms;
using MusicBeePlugin;

namespace ExamplePlugin
{
    [PluginFrontend]
    class Example : IPluginFrontend
    {
        void IPluginFrontend.Initialize(IMusicBeeAPI api, out int configPanelHeight) {
            configPanelHeight = 0;
            api.PluginStartup += PluginStartup;
        }

        private void PluginStartup(NotificationEventArgs args) {
            args.API.TrackChanged += TrackChanged;
        }

        private void TrackChanged(NotificationEventArgs args) {
            Console.WriteLine(args.RelatedFile.TrackTitle);
        }

        bool IPluginFrontend.PluginConfigure(Panel configPanel) {
            return false;
        }

        void IDisposable.Dispose() { }
    }
}
Title: Re: MusicBee API
Post by: boroda on July 16, 2011, 10:42:14 PM
Steven, for unclear reasons setting album/track rating (using MB API) to "5" or "5.0" actually sets it to 0.3 (half star is displayed instead of 5 stars).
Title: Re: MusicBee API
Post by: Steven on July 16, 2011, 10:48:35 PM
thats fixed for the next update
Title: Re: MusicBee API
Post by: boroda on July 17, 2011, 12:13:39 AM
Steven, doesn't MB currently send TagsChanged (including on changing 'Play count' and 'Skip count' tags) notification yet?
Title: Re: MusicBee API
Post by: Steven on July 17, 2011, 07:23:21 AM
it doesnt send any tag notification for play or skip count. It should for any when tags are changed by the user (incl rating) and saved to file.
see:
http://getmusicbee.com/forum/index.php?topic=3778.msg21175#msg21175

i havent uploaded the amended interface file, but the enum for the notifications are:
        TagsChanging = 10,
        TagsChanged = 11,
        RatingChanged = 12
Title: Re: MusicBee API
Post by: boroda on July 17, 2011, 10:25:53 AM
Well, could you add notification 'track is about to be changed'? It should be sent in exactly the same cases as 'track changed', but before track is really changed so one can retrieve all file properties and tags for changing track.
Title: Re: MusicBee API
Post by: Steven on July 17, 2011, 10:39:16 AM
there is already TrackChanged so you could grab the tags at that point
but i will add a PlayCountersChanged event (which includes SkipCount changing)
Title: Re: MusicBee API
Post by: boroda on July 17, 2011, 10:43:51 AM
there is already TrackChanged so you could grab the tags at that point
MB changes play count and skip count in very smart way. This tags may be changed in the middle of track playback.

but i will add a PlayCountersChanged event (which includes SkipCount changing)
Thanks.
Title: Re: MusicBee API
Post by: Steven on July 17, 2011, 11:28:28 AM
updated .exe to support PlayCountersChanged
http://www.mediafire.com/?6pu0aa45o44ixlc

i will post a full updated API source code examples later, but these are the changes to manually edit in the MusicBeeInterface file

enum PluginNotifyType
...
        TagsChanging = 10,
        TagsChanged = 11,
        RatingChanged = 12,
        PlayCountersChanged = 13

enum ReceiveNotificationFlags
...
        TagEvents = 0x04

to receive tag event notifications, in the Initialise section of your plugin
...
            about.ReceiveNotifications = (ReceiveNotificationFlags.PlayerEvents | ReceiveNotificationFlags.TagEvents);
Title: Re: MusicBee API
Post by: boroda on July 17, 2011, 04:16:21 PM
Steven, thanks. All works fine.
Title: Re: MusicBee API
Post by: boroda on July 22, 2011, 09:58:31 PM
Steven, how can I get rid of 'Info box' when I click 'Configure' in Prefs/Plugins? I wand to display my own dialog without default dialog.
Title: Re: MusicBee API
Post by: Elberet on July 23, 2011, 03:42:34 AM
Just return true from Configure and MusicBee assumes that you have handled configuration and won't show the default about dialog.
Title: Re: MusicBee API
Post by: boroda on July 23, 2011, 04:43:05 AM
Thanks, Elberet. So simple!
Title: Re: MusicBee API
Post by: Steven on August 14, 2011, 08:24:34 PM
API updated (get the interface definition file from the updated examples in the first post)

function to get all files matching a query in one call. The matching file paths are returned in one string, each path separated by a null char. You still need to call the query beforehand eg. Library_QueryFiles()
            string Library_QueryGetAllFiles();
            string NowPlayingList_QueryGetAllFiles();
            string Playlist_QueryGetAllFiles();

support for creating background tasks that show on the musicbee taskbar - you can create multiple tasks, but each one will be executed sequentially in a background thread so it doesnt interfere with the MusicBee GUI:

            mbApiInterface.MB_CreateBackgroundTask(new System.Threading.ThreadStart(Task1));

            private void Task1()
            {
                mbApiInterface.MB_SetBackgroundTaskMessage("some message");
                ....
            }

Title: Re: MusicBee API
Post by: boroda on August 15, 2011, 07:57:20 PM
Steven, I'm trying to play around with MB_CreateBackgroundTask function. Actually I didn't start from scratch and maybe my existing code interfere with new API, but I found some strange things:

1. ~50% of commands in my plugin depends on form's data (especially on generated preview, so I cant dispose/destroy/close command window), but if I didn't call Hide() method for form, then clicking on statusbar hangs MB UI.

2. If I hide form, then clicking on 'X' button on statusbar terminates background process, but double-clicking on rotating circle or statusbar text (single-clicking does nothing) hangs MB.

What I would want is to handle single-clicking on 'X' button (if possible - to correctly exit the file querying loop - but this is not very important) and that single-clicking on rotating circle should invoke Show() method of form, i.e I want to have 'Hide' button that should hide command window and clicking on rotating circle should restore the window.
Title: Re: MusicBee API
Post by: Steven on August 15, 2011, 08:14:03 PM
1) its not a good idea to access data in the form controls from a background thread (and infact if you try to do it from an app in the visual studio debugger in debug mode will result an "Illegal cross threaded operation" or something like that but perhaps it doesnt detect that condition from loaded dlls) - you should load the values into local values within the plugin scope. It might work fine though if you are only reading control values. If you mean double clicking then it sounds the same issue as 2

2) double clicking on status bar tries to open the parent form. I'm not sure what its doing as i dont provide any way for you to pass the parent form so i need to check that out.

To handle the user clicking X you can capture the ThreadAbortException and do the cleanup as approriate
Title: Re: MusicBee API
Post by: boroda on August 15, 2011, 08:51:56 PM
1) its not a good idea to access data in the form controls from a background thread
They weren't background threads initially! They became such in latest beta version. :)

If you mean double clicking then it sounds the same issue as 2
No, I meant even single-clicking.

2) double clicking on status bar tries to open the parent form. I'm not sure what its doing as i dont provide any way for you to pass the parent form so i need to check that out.
You can get object of delegate via delegate.Target, but you should implement some common class for background processes (maybe Form or subclass of Form). Or Mb should ignore double-clicking on statusbar at least (but certainly shouldn't hang up)

To handle the user clicking X you can capture the ThreadAbortException and do the cleanup as appropriate
Thanks. I'll probably try this but I'm mostly feel uncomfortable about terminating thread than actually need to do some cleanup.

EDIT:
Probably it can be useful that single-clicking on rotating circle in statusbar will invoke context menu with all queuing tasks, clicking on menu item should display appropriate window with possibility to change conditions or abort command.
Title: Re: MusicBee API
Post by: boroda on August 19, 2011, 11:00:26 AM
A bug: calling Library_QueryGetAllFiles (probably Library_QueryGetNextFile also and other querying functions) always reset statusbar text from number/size of currently displayed/selected files to number/size of all files in library.
Title: Re: MusicBee API
Post by: Steven on August 20, 2011, 10:09:57 AM
MB_CreateBackgroundTask has been amended to take an extra parameter, the owner form. You can pass null, but if it is supplied, then double clicking on the taskbar will unhide this form

mbApiInterface.MB_CreateBackgroundTask(System.Threading.ThreadStart handler, System.Windows.Forms.Form owner);

the updated interface definition file is available in the language templates from the first post.
Updated MusicBee.exe to support the additional parameter (if this link is dead, just get MusicBee.exe from latest weekly update)

http://www.mediafire.com/?m9y0ix1e679wpc5
Title: Re: MusicBee API
Post by: boroda on August 30, 2011, 09:16:52 PM
Steven, I've found a strange bug with updating tags of currently playing track using API. All tag changes made in tag editor are immediately reflected in MB UI. But tag changes made in background thread using API calls are not reflected until playback is finished or stopped. Though several tag updating API calls (for the same track) can make MB to display changes.

P.S. User VX reported that using 'Reencode tag' command of 'Additional tagging tools' plugin sometimes don't update tags in Inbox (and F5 doesn't help), but moving files to the library caused MB to display correct tags - I think it was the same issue.
Title: Re: MusicBee API
Post by: Steven on August 30, 2011, 10:01:40 PM
the GUI wouldnt be reliably updated until you call MB_RefreshPanels()
however if after you have called CommitTags() for a file its possible you could do some action in the MB gui yourself eg. scroll a track into view, it could show the new value but i dont think i can do anything about that
does that explain what you are seeing?
Title: Re: MusicBee API
Post by: boroda on August 31, 2011, 06:36:19 AM
No, Steven, all is fine with using RefreshPanels() and CommitTags() calls. There is a problem with sending notifications to plugin. That's what I've found out (only for updating tags of playing track):

1. Clicking 'save' button in docked tag editor if no tag was *actually* changed always sends TagsChanged message.
2. Clicking 'save' button if any tag was *actually* changed sends TagsChanged message only after second click. 
3. Updating tag by API call never generates TagsChanged message (if track is playing).

Very strange behavior, not documented and unexpected.

Processing of TagsChanging message seems to work fine, but I've found another issue: play and pause track, close MB, restart MB, *actually* change any tag of paused track in tag editor or commit tags for this track using API, close MB. You'll get 'Unable to open file for writing' error message.
Title: Re: MusicBee API
Post by: Steven on August 31, 2011, 09:10:21 PM
i dont understand what you mean by "second click"
it should be sending TagsChanging immediately when you click save in the tag editor. There isnt any logic to determine if any tags actually changed or not.
if the file is not playing the TagsChanged should be immediate, otherwise if the file is being played then when the song finishes

i've done a very simple test using the API and i am finding the TagsChanging/TagsChanged messages are consistent with the above. Could you give me some steps to follow via your plugin so i can reproduce this?
Title: Re: MusicBee API
Post by: boroda on September 02, 2011, 08:47:12 AM
i dont understand what you mean by "second click"
Click twice (probably with some delay) on 'save' button (in docked tag editor) or click 'save' button and reopen floating tag editor and click 'save' again.

it should be sending TagsChanging immediately when you click save in the tag editor. There isnt any logic to determine if any tags actually changed or not.
Yes, its quite right for TagsChanging event, but I spoke about TagsChanged in this case. BTW I can grab only not yet changed tags on TagsChanging event, so it's useless in my case.

if the file is not playing the TagsChanged should be immediate, otherwise if the file is being played then when the song finishes
I said that I have no problem with tracks that are not played when tags are changed. Please reread first part of my previous post about currently played tracks.

i've done a very simple test using the API and i am finding the TagsChanging/TagsChanged messages are consistent with the above. Could you give me some steps to follow via your plugin so i can reproduce this?
I'm doubtful that you want to test my plugin. This is simple modification of your example plugin (http://www.mediafire.com/?udlknhaohve0rjk) and this is source code (c#) (http://www.mediafire.com/?58mc4ne1mbumcb1) for it. This plugin just shows message box with 'Track title' value displayed if it receives TagsChanged notification. Please repeat steps 1-2 from my previous post with this plugin enabled.



PS For step 3 from my previous post I meant 'Updating tag by API call never generates TagsChanged message (if track is playing until track is finished playing)'.
Title: Re: MusicBee API
Post by: Steven on September 02, 2011, 09:52:45 AM
i understood you are referring to playing tracks. What i am saying is its intentional that TagsChanged only gets generated when the file is physically updated ie. when the song finishes. Thats why i created 2 events because the tags are not written to file immediately when a song is playing. Perhaps its better called TagsWritten instead
What i could do is ensure the cached values are made available from the API as soon as TagsChanging is generated

edit:
the change is made for the next update - so as soon as TagsChanging is triggered any metadata queries will return the updated tag values, whether the song is playing or not
Title: Re: MusicBee API
Post by: boroda on September 02, 2011, 11:27:25 PM
What i could do is ensure the cached values are made available from the API as soon as TagsChanging is generated
That's what I really would want.
Title: Re: MusicBee API
Post by: boroda on October 30, 2011, 06:35:32 AM
Steven, feature request. Could you add an option to Library_QueryFiles function to filter tracks by tags. Currently I need to filter only by AlbumArtist and Album tags, but it would be great if there will be opportunity to filter by any tags.
Title: Re: MusicBee API
Post by: kelsos on November 06, 2011, 10:46:52 PM
For some reason I have an issue with the repeat changing through the API. When I am calling Player_SetRepeat(RepeatMode.One); it goes to RepeatMode.None, any idea why that happens?
Title: Re: MusicBee API
Post by: Steven on November 07, 2011, 12:25:32 PM
i think that API actually only supports toggling between repeat None and repeat On.
repeat One isnt supported via the API.
Is that going to be a problem?
Title: Re: MusicBee API
Post by: kelsos on November 07, 2011, 12:41:30 PM
No not really. I just need to know how to implement the repeat change.
Title: Re: MusicBee API
Post by: Steven on November 07, 2011, 01:02:38 PM
calling that API with the RepeatMode.None or RepeatMode.All should work - if it doesnt then its a bug (also make sure you are using the latest beta as i do recall at one point that api call wasnt refreshing the GUI)
Title: Re: MusicBee API
Post by: e-motiv on November 08, 2011, 01:33:49 PM
Furhter help with API problems here would be appreciated from anyone:
http://getmusicbee.com/forum/index.php?topic=3870.msg26454#msg26454
Title: Re: MusicBee API
Post by: kelsos on November 13, 2011, 12:52:39 PM
Is there a way to change the Playing track in the Now Playing List to a specific track (being in the list) directly by specifying the track location you get by a query? I tried with NowPlayingList_PlayNow but it will alter the Playlist so it is not a solution.
Title: Re: MusicBee API
Post by: Steven on November 13, 2011, 01:24:21 PM
i will be looking to enhance the API for the 1.4 release so i can look at it later in the week
Title: Re: MusicBee API
Post by: Steven on November 13, 2011, 04:39:46 PM
i've made a change that will be included in the final 1.3 release - this is actually how i intended originally anyway

NowPlayingList_PlayNow(url) now searches the now playing list and if the file is located then the now playing list will jump to that file.
Otherwise the now playing list is reset as is the case now

http://www.mediafire.com/?3xsjaerhhe5j089
Title: Re: MusicBee API
Post by: kelsos on November 13, 2011, 04:42:19 PM
Thanks Thanks :D I can continue with the playlist feature of the remote control now :D
Title: Re: MusicBee API
Post by: e-motiv on November 17, 2011, 03:02:33 PM
It seems "RatingChanged" does not work for me.
"TagsChanging" and "TagsChanged" do work for me. Also, my settings dó save ratings to file (if it matteers at all).
Anything I ignore ?
Title: Re: MusicBee API
Post by: Steven on November 17, 2011, 05:21:21 PM
it currently doesnt notify rating changes when done in the tag editor (will do for the next update)
it should be notifying if you update in the main panel or player control panel
Title: Re: MusicBee API
Post by: e-motiv on November 17, 2011, 05:48:41 PM
I see.  And indeed, it does work in the player control. But it does not work in the main panel though (e.g. Music Library and clicking on 4 stars).
But on the other side it DOES work where I most need it: When changing the now playing song through a keyboard shortcut! I did not bother to check that out before for some weird reason.  ::)
So, for me you don't have to fix this in the tag editor (unless someone will want that with my plugin later on, but I doubt it).

Something else  ;D  What's the best way to get the previous rating on RatingChanged?
(So I can let my speaking addon say like "Rating changed from 1 to 3")

Thanks
Title: Re: MusicBee API
Post by: Steven on November 17, 2011, 06:29:02 PM
can you confirm its not working when clicking a rating in the main panel - i see no reason for it not to work, unless you are refering to using the tag editor docked in the main panel

i've updated the API as follows:
- Rating change now notified when changed in the tag editor
- you can now set tags on http:// files (still need to call Library_CommitTagsToFile but it just updates the internal MB cache)
- MB_AddMenuItem now returns the ToolStripItem object that was created

the updated interface definition file is in the first post

updated MusicBee.exe:
http://www.mediafire.com/?d3vv22moj53b6g3
Title: Re: MusicBee API
Post by: e-motiv on November 17, 2011, 10:48:53 PM
Thanks for the updates!  I will probably only be able to continue on the weekend.

But already this: For one reason or another a lot of my library files where not found (with a blue exclamation mark) (though they are there). Anyway, it was only with those that the ratingchanged did not work (only the other tagschanged). Did not notice before.
I don't know if that's how you intended it for missing(?) songs.  For me it's the same.
Title: Re: MusicBee API
Post by: Antonski on November 18, 2011, 12:24:16 AM
can you confirm its not working when clicking a rating in the main panel - i see no reason for it not to work, unless you are refering to using the tag editor docked in the main panel

i've updated the API as follows:
- Rating change now notified when changed in the tag editor
- you can now set tags on http:// files (still need to call Library_CommitTagsToFile but it just updates the internal MB cache)
- MB_AddMenuItem now returns the ToolStripItem object that was created

the updated interface definition file is in the first post

updated MusicBee.exe:
http://www.mediafire.com/?d3vv22moj53b6g3

Is Rating change also notified when done from player control panel as well? Because, usually I rate the tracks while listening (by clicking the stars in control panel or in main panel, Album and tracks layout), I don't open explicitly Tag editor.
Title: Re: MusicBee API
Post by: Steven on November 18, 2011, 07:05:02 AM
Is Rating change also notified when done from player control panel as well? Because, usually I rate the tracks while listening (by clicking the stars in control panel or in main panel, Album and tracks layout), I don't open explicitly Tag editor.
its anywhere the rating is changed
Title: TagsChanged without previous RatingChanged
Post by: e-motiv on November 25, 2011, 05:49:04 PM
Changing ratings via the editor triggers Notification TagsChanged, but NOT RatingChanged.
(It dóes trigger both with other ways of changing tags.)

Problem for my specific plugin (http://getmusicbee.com/forum/index.php?topic=4941.0) is that I cannot know on TagsChanged if the rating was changed or not, and thus not inform the user of it. 

But it's actually not that important. So íf this is something to fix, it's totally OK to put it on the long term list.  Just wanted to inform.
Title: Re: MusicBee API
Post by: Steven on November 26, 2011, 09:06:15 AM
can you confirm the version you are using as its working fine for me when changing the rating in the tag editor in my test plugin
Title: Re: MusicBee API
Post by: Steven on November 26, 2011, 09:52:34 AM
actually dont worry as i found the reason
Title: Re: MusicBee API
Post by: kelsos on January 07, 2012, 07:12:04 PM
May I ask, is there a way to access the lyrics MB retrieved for the playing track through the API?
Title: Re: MusicBee API
Post by: Steven on January 07, 2012, 07:42:15 PM
yes - for lyrics of the playing track:
NowPlaying_GetLyrics

for lyrics for a specific file:
Library_GetLyrics

they just return current values and dont atempt to download them if not already downloaded
Title: Re: MusicBee API
Post by: kelsos on January 07, 2012, 07:54:10 PM
I was trying the NowPlaying_GetLyrics before, however it returns nothing when called, even though I can see the lyrics on the player just fine.
Title: Re: MusicBee API
Post by: Steven on January 08, 2012, 08:28:31 AM
Library_GetLyrics and NowPlaying_GetLyrics were only returning lyrics directly associated with the music file
I have changed it so NowPlaying_GetLyrics retrieves lyrics from the web when no lyrics are directly associated (and if the user has enabled web-retrieval for lyrics) so its consistent with the Now Playing panel.
Library_GetLyrics is unchanged from the current behavior.
Title: Re: MusicBee API
Post by: Steven on February 22, 2012, 07:56:39 PM
these new additions require version 2 of musicbee

VB Source:
http://www.mediafire.com/?32z0uhc2l75cuth

C# Source:
http://www.mediafire.com/?tc2rfly0rpkrr7g

C++ Source - hasnt been updated, so contact me if you need to use the new features



public void MB_RegisterCommand(string command, EventHandler handler)
public font Setting_GetDefaultFont()
public bool Player_GetShowTimeRemaining()
public int NowPlayingList_GetCurrentIndex()
public string NowPlayingList_GetFileUrl(int index)
public string NowPlayingList_GetFileProperty(int index, FilePropertyType type)
public string NowPlayingList_GetFileTag(int index, MetaDataType type)

MB_RegisterCommand - enables a hotkey to be assigned to a plugin callback function, where "command" is a description of the command that will be displayed in the HotKey preferences
Setting_GetDefaultFont - returns the default font set in MusicBee
NowPlayingList_GetCurrentIndex - returns the index in the now playing list of the current playing track
NowPlayingList_GetFileUrl, NowPlayingList_GetFileProperty and NowPlayingList_GetFileTag allow you to get information for a track in the now playing list
Title: Re: MusicBee API
Post by: boroda on February 23, 2012, 08:11:29 AM
Steven, thanks for update. Will old AddMenuItem function also register hotkey now (the second parameter is a hotkey description, but it was never used by MB earlier)?
Title: Re: MusicBee API
Post by: Steven on February 23, 2012, 09:08:51 AM
yes good point - i will do that
Title: Re: MusicBee API
Post by: e-motiv on April 10, 2012, 01:40:30 PM
Steven, I was updating my "speak back" plugin so now it could also say "from" which rating you are changing.  E.g. "Rating changed from 1 to 4".
So, logically, I used NotificationType.TagsChanging to get old value, but I discovered that doesn't work on keyboard shortcuts. (It does work with context menu editing.)
So is there another way to get the old rating from the track you are changing?
MB 2.0.4467
Title: Re: MusicBee API
Post by: e-motiv on April 25, 2012, 02:30:50 PM
Steven, I was updating my "speak back" plugin so now it could also say "from" which rating you are changing.  E.g. "Rating changed from 1 to 4".
So, logically, I used NotificationType.TagsChanging to get old value, but I discovered that doesn't work on keyboard shortcuts. (It does work with context menu editing.)
So is there another way to get the old rating from the track you are changing?
MB 2.0.4467
Bump?
Title: Re: MusicBee API
Post by: ddelella on April 28, 2012, 04:30:30 PM
I am glad to see the API is available in C# and VB.NET.  Might I suggest an API section added to the website for documentation and easier downloading of the latest version.  Forums are never the best way to deliver updates because you have to search for the last post that contained a release plus you have to read for the latest changes.  I think jQuery probably does the best job in online documentation and ease of finding the API download.  Just a suggestion but great job with the application.  I am a developer and glad to see the move to .NET4. 

Another idea is possibly releasing a built in template for Visual Studio that sets up a plugin project.  This way you could build in certain features to the plugins which are required by the application, like the window design, resizing, and proper API references.  This just leave the design to the developer.

Thanks
Title: Re: MusicBee API
Post by: kelsos on June 02, 2012, 01:01:04 PM
I keep getting a System.NullReferenceException when I use the NowPlaying_GetLyrics() in the v2 betas, any ideas?
Title: Re: MusicBee API
Post by: Steven on June 02, 2012, 06:24:10 PM
the theater mode plugin is making use of that API without problems as far as i know.
It can return a null value (not sure if it always did that, and when that happens you could call NowPlaying_GetDownloadedLyrics() immediately afterwards and again after receiving NotificationType.NowPlayingLyricsReady)
if you are sure you are triggering an exception within MusicBee let me know the artist and title you are testing
Title: Re: MusicBee API
Post by: kelsos on June 03, 2012, 12:23:22 AM
Are the calls you mentioned above (Like GetDownloadedLyrics) in a version newer than this one: PluginInfoVersion = 1, MinInterfaceVersion = 6, MinApiRevision = 10? if so could you upload the updated interface file for c#?
Title: Re: MusicBee API
Post by: Steven on June 03, 2012, 08:22:56 AM
sent you a PM with the API interface - i will load this for everyone at a later date
Main code:
lyrics = mbApiInterface.NowPlaying_GetLyrics();
if (String.IsNullOrEmpty(lyrics) && mbApiInterface.ApiRevision >= 17) {
    // this can still return null, but calling it will trigger a notification when the lyrics have been downloaded
    lyrics=mbApiInterface.NowPlaying_GetDownloadedLyrics();
}

ReceiveNotification
NotificationType.NowPlayingLyricsReady:
            If (mbApiInterface.ApiRevision >= 17)
                xx = mbApiInterface.NowPlaying_GetDownloadedLyrics();
 
Title: Re: MusicBee API
Post by: Steven on June 05, 2012, 09:10:14 AM
first post updated with links to the updated API interface.
See prior posts for explanations of the new API methods
Title: Re: MusicBee API
Post by: e-motiv on August 25, 2012, 11:48:26 AM
Steven, I was updating my "speak back" plugin so now it could also say "from" which rating you are changing.  E.g. "Rating changed from 1 to 4".
So, logically, I used NotificationType.TagsChanging to get old value, but I discovered that doesn't work on keyboard shortcuts. (It does work with context menu editing.)
So is there another way to get the old rating from the track you are changing?
MB 2.0.4467
Bump?
Bump. Any fixes or insights on this?
Title: Re: MusicBee API
Post by: Steven on August 25, 2012, 01:52:19 PM
i have added
PluginNotifyType.RatingChanging

you will need this version of MusicBee (it will be in the next weekly update)
http://musicbee.niblseed.com/V2/MusicBee_Exe_Patched.zip

and the updated interface file
C#:
http://www.mediafire.com/?5727cyc53h3ja82
or VB:
http://www.mediafire.com/?652mh6o6l0aowak
Title: Re: MusicBee API
Post by: e-motiv on August 25, 2012, 06:24:51 PM
Thank you!
Title: Re: MusicBee API
Post by: e-motiv on November 03, 2012, 07:45:24 PM
i have added
PluginNotifyType.RatingChanging
I have finally tried it, but it still doesn't work.  It also gives me the rating AFTER having changed it, not BEFORE.  (Capitals not mean as shouting, just highlight.).
On NotificationType.RatingChanging, I do oldrating = mbAPI.Library_GetFileTag(sourceFileUrl, MetaDataType.Rating); , but it still tells the new rating in stead of the old. 
And even worse, before I think it did work (with tagschanging) on context editing, but now it doesn't work anywhere.  Any tips?
Title: Re: MusicBee API
Post by: slimmeke on November 19, 2012, 07:05:41 PM
Is it possible to update the C++ library so I can use it for making a plugin.
I'm writing a plugin for the Logitech G15, G19 LCD. But the only language they support is C++.
Title: Re: MusicBee API
Post by: Steven on November 19, 2012, 07:10:37 PM
Its a lot of effort for me to maintain the C++ library and as no one appeared to be using it i have stopped adding to it.
But although the C++ library doesnt have the newer API calls it should still work, and has the basic functions that allow you to retrieve the current playing track, lyrics and picture, and control playback.
So if its missing particular API calls you need then let me know
Title: Re: MusicBee API
Post by: slimmeke on November 23, 2012, 04:22:40 PM
Ok Tnx for you answer.

I have only one problem with tha API.
When I compile the C++ example of the Api I get an error.
I can't activate the plugin because of following error:
Dll entry point: Initialise was not found.
But there is an Initialise methode.
I hope somebody can help me with this problem.
Title: Re: MusicBee API
Post by: Steven on November 23, 2012, 09:46:38 PM
can you be more specific about what error you get when compiling.
I am using Visual C++ - the example was done with v9, but i only have v10 now - it still compiles and runs fine for me.
As a guess for the missing entry point, the TestDll.def contains definitions for the entry points, and needs to be set as the "Module definition file" in the C++ linker/input settings (which is it when using the example project file)
Title: Re: MusicBee API
Post by: e-motiv on November 25, 2012, 04:28:40 PM
Steven,    I believe PluginNotifyType.RatingChanging is still not working properly (MB 2.0.4663).
 It seemed most of the time not working and very randomly working.  To help you discover what's wrong, I traced it a bit.
Here are the results of what a serie that I think could be reproducible.  Notice that only the first rating changing of the serie did it right! All the others tell the future rating:

For the record, in all the changing of ratings below, I always did it via key shortcut.

1 .restart MB,  playing song,  changng rating from "no rating" -> 1:
 RatingChanging - Rating: norating
 RatingChanged - Rating: 1
2. While still playing same song, 1->2:
 RatingChanging - Rating: 2
 RatingChanged - Rating: 2
3. Playing another song, switching back to above song, 2->1:
 RatingChanging - Rating: 1
 RatingChanged - Rating: 1
4. Playing a never played song (since MB started), no rating->1:
 RatingChanging - Rating: 1
 RatingChanged - Rating: 1

(I tried other ways with failed results, though different series)

Code
public void ReceiveNotification(string sourceFileUrl, NotificationType type)
{
string debug = "", rating ="";
// perform some action depending on the notification type
rating = mbAPI.Library_GetFileTag(sourceFileUrl, MetaDataType.Rating);
rating = rating=="0,0"?"0":rating==""?"norating":rating;
switch (type)
{
case NotificationType.PluginStartup:
// perform startup initialisation
myPlay(about.Name+" launched");
break;
case NotificationType.TagsChanging:
debug = " - Rating: " + rating;
myPlay("tagschanging");
break;
case NotificationType.RatingChanging:
debug = " - Rating: " + rating;
//myPlay("ratingchanging");
break;
case NotificationType.RatingChanged:
debug = " - Rating: " + rating;
myPlay("ratingchangedfrom");
myPlay("2"); //function not as the numbern but the word,  "to" :-)
myPlay(rating);
break;
case NotificationType.TagsChanged:
//debug = " - Rating: " + rating;
myPlay("changessaved");
break;
}
if (debug!="") Out(type + debug); //debug
}
Title: Re: MusicBee API
Post by: slimmeke on November 30, 2012, 01:05:39 PM
The C++ APi works tnx.
But I have a little question.
Is it possible to know the time of the current possition of the playing song?
Title: Re: MusicBee API
Post by: Steven on November 30, 2012, 08:07:44 PM
Player_GetPosition()
Title: Re: MusicBee API
Post by: e-motiv on December 23, 2012, 04:04:52 PM
Steven,    I believe PluginNotifyType.RatingChanging is still not working properly (MB 2.0.4663).
Bump?
Or am I doing something wrong? (Details in my post above.)
Title: Re: MusicBee API
Post by: kogash on December 29, 2012, 06:52:25 PM
Steven, are query parameters ready yet?

 if they are can you show us an example? I'm not able to use the autoplaylists xml to filter anything!
Title: Re: MusicBee API
Post by: Steven on December 29, 2012, 07:14:52 PM
are you looking to create your own custom query or is it the case that you are trying to retrieve auto-playlist files using Playlist_QueryFiles(filename).
If its the later then make sure the filename includes the full path ending with .xuatopf

if you are wanting to create your own custom queries then use this syntax - i know its not great and quite limited:
Library_QueryFiles("field=XXXX")
for multiple "and" conditions, separate each one by a null character '\0'
Library_QueryFiles("artist=XXXX" + '\0' + "album=YYYY")
there is no "or" syntax currently supported

another possibility for full flexibility would be for you to generate your own auto-playlist - they are just xml files, and then use the Playlist_QueryFiles(filename) API call to retrieve the files.
The key elements in the xml are:
  <Source Type="1">   this indicates the files are retrieved from the library
  <Conditions CombineMethod="All">    All or Any
  <Condition Field="FileDateAdded" Comparison="InTheLast" Value="6m" />
  </Conditions>

However the current API behavior is to only load cached playlist files that are in the Playlists folder of the musicbee library. I could easily change that so you could load your own generated .xautopf file on the fly
Title: Re: MusicBee API
Post by: kogash on December 29, 2012, 08:16:27 PM
Library_QueryFiles("field=XXXX")
for multiple "and" conditions, separate each one by a null character '\0'
Library_QueryFiles("artist=XXXX" + '\0' + "album=YYYY")
there is no "or" syntax currently supported

That! But i need something like the quicksearch that is in the main window, it uses "all fields" as default, is there a metafield for "all fields"?
must i escape the query text anyway?

The Playlist_QueryFiles(filename) is not usefull because I must generate the xml on runtime so it will not be (and must not be) cached nor shown in the ui

Thanks a lot for your responses and your hard work!
Title: Re: MusicBee API
Post by: Steven on December 29, 2012, 08:38:38 PM
generating the xml could be saved to a non-cached file so wouldnt update the UI or the API could take the xml string directly.
But in any case there is no syntax (xml or existing query parameter) to support searching all fields for text and i am not able to change anything at the moment anyway - it wouldnt be until after the new year
Title: Re: MusicBee API
Post by: e-motiv on December 29, 2012, 09:06:44 PM
Steven,    I believe PluginNotifyType.RatingChanging is still not working properly (MB 2.0.4663).
Bump?
Or am I doing something wrong? (Details in my post above.)
I really feel ignored   :'(
Title: Re: MusicBee API
Post by: Steven on December 29, 2012, 09:27:24 PM
the reason the rating is not the old value is because the notifications are asynchronous, so by the time you receive it, any call backs to retrieve the current rating will have in likelyhood already changed. Can you let me know what you are trying to achieve
Title: Re: MusicBee API
Post by: slimmeke on December 31, 2012, 12:13:26 PM
What value will mbApiInterface.NowPlaying_GetArtwork() return? Is it a url to the artwork or a encrypted string with the artwork in it?
Title: Re: MusicBee API
Post by: Steven on December 31, 2012, 01:24:28 PM
i didnt think anyone was using it, so i changed it to return a url as the picture can be very big for an encoded string.
If the API revision in the plugin interface file mbApiInterface.ApiRevision is <= 25 then its using the old way
Title: Re: MusicBee API
Post by: Steven on January 01, 2013, 02:21:50 PM
Library_QueryFiles("field=XXXX")
for multiple "and" conditions, separate each one by a null character '\0'
Library_QueryFiles("artist=XXXX" + '\0' + "album=YYYY")
there is no "or" syntax currently supported

That! But i need something like the quicksearch that is in the main window, it uses "all fields" as default, is there a metafield for "all fields"?
must i escape the query text anyway?

The Playlist_QueryFiles(filename) is not usefull because I must generate the xml on runtime so it will not be (and must not be) cached nor shown in the ui

Thanks a lot for your responses and your hard work!
Library_QueryFiles(query) has been enhanced so the query parameter can now be an xml string using the same syntax as the xml for auto-playlist files (suggest you create an auto-playlist to get the xml you want to generate) - however you only really need the Conditions and Condition elements. I forgot that auto-playlists can already search all fields for text by setting the field to "Any field" (=None in the xml) and the comparison type to "Is" or "Is any of"
Its in the next 2.1 update
Title: Re: MusicBee API
Post by: kogash on January 01, 2013, 04:31:34 PM
i didnt think anyone was using it, so i changed it to return a url as the picture can be very big for an encoded string.
If the API revision in the plugin interface file mbApiInterface.ApiRevision is <= 25 then its using the old way


I was using it, it was very usefull but strange way to pass an image. I prefer the url way...  but I suggest you that in future api updates don't break functionality based on magic version numbers, IMHO it's much better to have:

library_getArtwork(string fileurl) <- returns base64
library_getArtworkUrl(string fileurl) <- new function returns url.

This way you I make a plugin that supports both musicbee 2 and musicbee 2.1
Title: Re: MusicBee API
Post by: Steven on January 01, 2013, 09:28:50 PM
i have added this API method to move files in the now playing list. Its in the next 2.1 update

public bool NowPlayingList_MoveFiles(int[] fromIndices, int toIndex)

where fromIndices is the 0 based position of the file(s) to be moved, and toIndex is the index to move after. That means to insert as the first item, you need to set toIndex to -1

When i make the update available, the included example file has a suggested approach for accomodating users still using MB v2.0 who you might want to offer reduced functionality with the older api methods. The issue with using the latest API version is it will crash MBv2.0 with a memory violation error when initialising using this code:
Code
                mbApiInterface = (MusicBeeApiInterface)Marshal.PtrToStructure(apiInterfacePtr, typeof(MusicBeeApiInterface));
the suggested approach is:
to follow
Title: Re: MusicBee API
Post by: Steven on January 03, 2013, 11:02:48 PM
api interface file and example updated in the first post

as well as the new NowPlayingList_MoveFiles() API method described above, the example files have been updated to support MusicBee version 2.0 and 2.1. If the host is MusicBee 2.0, any of the API methods after revision 25 will be null. The initialisation sequence is now:
            mbApiInterface = new MusicBeeApiInterface();
            mbApiInterface.Initialise(apiInterfacePtr);
Title: Re: MusicBee API
Post by: e-motiv on January 07, 2013, 05:13:43 PM
the reason the rating is not the old value is because the notifications are asynchronous, so by the time you receive it, any call backs to retrieve the current rating will have in likelyhood already changed. Can you let me know what you are trying to achieve

I thought you actually introduced NotificationType.RatingChanging (edit-correction) just for my retrieving old values?

So, I am still  trying to achieve the same thing as my initial request
   http://getmusicbee.com/forum/index.php?topic=1972.msg35234#msg35234
After which you introduced PluginNotifyType.RatingChanging
    http://getmusicbee.com/forum/index.php?topic=1972.msg41272#msg41272
Title: Re: MusicBee API
Post by: e-motiv on February 02, 2013, 11:26:46 PM
Steven, any insight on the above?  This at first sight simple topic has meanwhile been a while and is spread along this thread. If you want, I can assemble previous specific posts in a separate thread so you can have a better view of all the things said/done before?
Title: Re: MusicBee API
Post by: slimmeke on February 06, 2013, 01:59:38 PM
What is the newest version of the API (C#) and where can I find it? I use now revision 27 and I can't get any notification to work (only the startup notification works.

And I don't use startpOnly in the ReceiveNotifications. I use:
about.ReceiveNotifications = (ReceiveNotificationFlags.PlayerEvents | ReceiveNotificationFlags.TagEvents);

The notification method looks like this:

 public void ReceiveNotification(string sourceFileUrl, NotificationType type)
        {
            // perform some action depending on the notification type
            switch (type)
            {
                case NotificationType.PluginStartup:

                    if (logitech == null)
                    {
                        logitech = new Logitech();
                        logitech.connect();

                        if (!logitech.connected)
                        {
                            Close(PluginCloseReason.StopNoUnload);
                        }
                    }
                    break;

                case NotificationType.PlayStateChanged:

                    if (logitech != null)
                    {
                        switch (mbApiInterface.Player_GetPlayState())
                        {
                            case PlayState.Playing:

                                logitech.changeState(PlayState.Playing);

                                if (!logitech.getFirstTime())
                                {
                                    logitech.setPosition(mbApiInterface.Player_GetPosition());
                                    logitech.setDuration(mbApiInterface.NowPlaying_GetDuration());
                                }
                                break;
                            case PlayState.Paused:
                                if (!logitech.getFirstTime())
                                {
                                    logitech.changeState(PlayState.Paused);
                                }
                                break;
                            case PlayState.Stopped:
                                if (!logitech.getFirstTime())
                                {
                                    logitech.changeState(PlayState.Stopped);
                                }
                                break;
                            case PlayState.Loading:
                                if (!logitech.getFirstTime())
                                {
                                    logitech.changeState(PlayState.Loading);
                                }
                                break;
                            case PlayState.Undefined:
                                if (!logitech.getFirstTime())
                                {
                                    logitech.changeState(PlayState.Undefined);
                                }
                                break;
                        }
                    }
                    break;

                case NotificationType.TrackChanged:
                    string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                    string album = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);
                    string title = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
                    string artwork = mbApiInterface.NowPlaying_GetArtwork();

                   
                    logitech.changeArtistTitle(artist, album, title, artwork, mbApiInterface.NowPlaying_GetDuration(), mbApiInterface.Player_GetPosition());
                    break;
            }
        }



It this a bug or is it my source??
Title: Re: MusicBee API
Post by: Steven on February 06, 2013, 06:29:18 PM
the most recent API interface is in the first post, but any updates to it is backwards compatible.
Most of the available existing plugins make use of either the tag or player events and no problems have been reported.
Looking at the code, it appears correct  - in fact i thought you had this working a few weeks ago.
Maybe your plugin is crashing?
Title: Re: MusicBee API
Post by: slimmeke on February 06, 2013, 06:51:49 PM
Yes it works in my previous version of the plugin. But now I'm rewriting the plugin in C# because of the problems using the Logitech SDK in a C++ dll.
Title: Re: MusicBee API
Post by: Steven on February 07, 2013, 07:06:48 AM
check out boroda74's "Advanced Tagging Tools" plugin which has c# source code posted in the first post of that plugin topic
Title: Re: MusicBee API
Post by: boroda on February 07, 2013, 07:28:18 AM
Source code above looks good.

check out boroda74's "Advanced Tagging Tools" plugin which has c# source code posted in the first post of that plugin topic
My plugin uses only NotificationType.PluginStartup, NotificationType.PlayCountersChanged, NotificationType.TagsChanged and NotificationType.RatingChanged events.
Title: Re: MusicBee API
Post by: boroda on February 07, 2013, 07:36:39 AM
Well, I've slightly modified my plugin to display message box in case of NotificationType.PlayStateChanged event. No problem. But sometimes plugin received NotificationType.PlayStateChanged event twice when I pressed pause/next/prev. buttons.
Title: Re: MusicBee API
Post by: slimmeke on February 07, 2013, 09:59:25 AM
Tnx guys the problem has been solved.
Title: Re: MusicBee API
Post by: jorgejiro on February 23, 2013, 04:33:56 PM
Hi all,

I'm trying to create a plugin that I used in winamp, when I had not discovered yet the best music player: MusicBee!! :)

The plugin is very simple: it captures a global hotkey (Win+W for example), and send the current song to the recycle bin and plays the next song in the current playlist.

I've downloaded the API c# project, and I've tried to build it, but it doesn't work the way I want.

I've tested my plugin, but only works if I had disabled/enabled it via MusicBee Preferences menu, so I need some kind of advice because it's annoying having to disable and enable the plugin in every session in order to use it  ;)



My question is: There is a way to register a global hotkey via MusicBee API, so I can capture this hotkey and do my stuff?



You can see my source code in BitBucket:
https://bitbucket.org/jorgejiro/musicbee-sendtorecyclebinplugin

The "KeyboardHook.cs" class assigns/detects global hotkeys.

The event function moves to the next song, and send the file to the recycle bin.

        void hook_KeyPressed(object sender, MusicBeePlugin.KeyboardHook.KeyPressedEventArgs e)
        {

            string fileUrl = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Url);

            if (mbApiInterface.NowPlayingList_IsAnyFollowingTracks())
            {
                mbApiInterface.Player_PlayNextTrack();
            }
            else
            {
                mbApiInterface.Player_Stop();
            }
            FileOperationAPIWrapper.MoveToRecycleBin(fileUrl);
        }


Title: Re: MusicBee API
Post by: Steven on February 23, 2013, 05:01:33 PM
i had a quick look:
- remove from the Initialise() function - you already have it in the PluginStartup event which is where it should be
Code
            // register the event that is fired after the key press.
            hook.KeyPressed += new EventHandler<MusicBeePlugin.KeyboardHook.KeyPressedEventArgs>(hook_KeyPressed);
            // register the control + alt + F12 combination as hot key.
            hook.RegisterHotKey(MusicBeePlugin.KeyboardHook.ModifierKeys.Win, Keys.W);
- in the Initialise() function set
Code
about.ReceiveNotifications = ReceiveNotificationFlags.StartupOnly
- i dont know if this matters to your function or not, but the PluginStartup notification (and any other notifications) are called on a separate thread to the main MusicBee GUI thread. It doesnt matter for calling MB functions from the plugin but it might matter to your keyboard handler
- you can register a command from which the user can assign a hotkey in the Hotkey preferences (or assign a command button) - its more flexible if you did it this way rather than registering your own hotkeys
Code
mbApiInterface.MB_RegisterCommand("Playback: Delete Current Track and Play Next", AddressOf functionToDoThis)
Title: Re: MusicBee API
Post by: jorgejiro on February 23, 2013, 05:49:38 PM
YEESSSS!

It works, thank you Steven for your quick response and great work!

I've used the way you told me, registering the command using "MB_RegisterCommand" :)

Thank you very much! I suppose I have to publish it under the "Plugins" sections...
Title: Re: MusicBee API
Post by: boroda on March 09, 2013, 12:06:25 PM
Steven, is it possible to read 'Loved'/'Banned' tags with current API?
Title: Re: MusicBee API
Post by: Steven on March 09, 2013, 12:18:58 PM
yes, its already in the interface definition file:
public enum MetaDataType
  RatingLove = 76

with returns "L", "B" or blank

if you want to set the value, you can but it only updates the cache.
If you want it to update last.fm as well then send me a PM
Title: Re: MusicBee API
Post by: boroda on March 09, 2013, 12:20:37 PM
yes, its already in the interface definition file:
public enum MetaDataType
  RatingLove = 76

with returns "L", "B" or blank
Thank you
Title: Re: MusicBee API
Post by: slimmeke on March 22, 2013, 09:48:56 AM
Hey

I have 2 problems with the API at the moment. When the user changed the tags of the current playing track hte API must hit "NotificationType.TagsChanged" but in my case it doesn't. Is this a known bug or is it my code?
The code below is my code for it:
     case NotificationType.TagsChanged:
                case NotificationType.NowPlayingArtworkReady:
                 case NotificationType.RatingChanged:
                case NotificationType.TrackChanged:
                    string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                    string album = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);
                    string title = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
                    string artwork = mbApiInterface.NowPlaying_GetArtwork();
                    string rating = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Rating);
                    string playlist = mbApiInterface.Playlist_QueryGetAllFiles();

                    logitech.changeArtistTitle(artist, album, title, rating, artwork, mbApiInterface.NowPlaying_GetDuration()/1000, mbApiInterface.Player_GetPosition()/1000);
                    break;
            }

Second problem is setting the rating of the current playing track. I use following code but it doesn't work.

foalt number = 0.5f;
String url = mbApiInterface.NowPlaying_GetFileUrl();
            mbApiInterface.Library_SetFileTag(url, MetaDataType.Rating, number.ToString());

Can someone help me with those problems. Tnx a lot for your time.
Title: Re: MusicBee API
Post by: boroda on March 22, 2013, 10:21:55 AM
TagsChanged event is fired when tags are actually written to file. For currently played file it will be when next track is played. TagsChanging event is fired when new tags values are enqueued for writing. For tracks which are not played TagsChanged and TagsChanging events are identical.   
Title: Re: MusicBee API
Post by: slimmeke on March 22, 2013, 11:08:11 AM
Oh didn't know that. Tnx for it.

Is this also why the rating doesn't work or is it an other problem??
Title: Re: MusicBee API
Post by: slimmeke on March 24, 2013, 10:20:54 AM
Is there a NotificationType for changing the settings like repeat, AutoDj, ...? I have found it only for the autoDj but not for the other settings that can be changed using this API.
Title: Re: MusicBee API
Post by: Steven on March 24, 2013, 11:17:40 AM
i will put a notification in the next 2.1 update
just add these enums to public enum NotificationType
            PlayerRepeatChanged = 20,
            PlayerShuffleChanged = 21
Title: Re: MusicBee API
Post by: slimmeke on March 24, 2013, 11:29:06 AM
Tnx for your support.
But sorry for asking is it possible to also add a Notification type for enabling and disabling the equaliser?
If this added to the API than I can make my plugin even better :).

Tnx Steven for your great work.
Title: Re: MusicBee API
Post by: Steven on March 24, 2013, 11:44:25 AM
you can already get the auto-dj notification
        AutoDjStarted = 3
        AutoDjStopped = 4

i have also added
            PlayerEqualiserOnOffChanged = 22,
            PlayerScrobbleChanged = 23
Title: Re: MusicBee API
Post by: slimmeke on March 24, 2013, 11:50:25 AM
Tnx for adding this.
Title: Re: MusicBee API
Post by: slimmeke on March 26, 2013, 06:26:08 PM
I think I have found 2 bugs in the API or in MusicBee.
When I do "mbApiInterface.Player_SetRepeat(RepeatMode.One);" MusicBee will set repeat to All instead of One.
And when I do:
 String url = mbApiInterface.NowPlaying_GetFileUrl();
 mbApiInterface.Library_SetFileTag(url, MetaDataType.Rating, number.ToString());
MusicBee does not change the rating of the track.

Is this an issue or is it my code?
Title: Re: MusicBee API
Post by: boroda on March 26, 2013, 07:27:48 PM
Not sure about 1, didn't test it. But I definitely using 2 in my plugin. There is one issue with rating: if rating <= 5 when writing then rating is multiplied by 20. Read rating belongs to scope 5-100.
Title: Re: MusicBee API
Post by: slimmeke on March 31, 2013, 03:00:34 PM
I have tested rating with rang of 5-100, 0-5, 0-10, ... but nothing works. :-[
Title: Re: MusicBee API
Post by: boroda on April 15, 2013, 09:54:55 PM
1. Steven, are TagsChanging and TagsChanged events sent to plugins if 'Love' (and other database-only) field is changed?
2. Could some event be fired if track properties (eg. 'Track Gain') are changed?
3. No rating should be no value, but it seems that API returns 0 for no rating.
Title: Re: MusicBee API
Post by: Steven on April 17, 2013, 06:40:31 PM
1. having a look at the code no its not - i am ok with adding the tag events for that
2. if i make it a general file properties event then its a lot of places affected so can you be specific about what you want it for
3. i havent checked but if true when i look at this i will change it to -1 (but i am surprised thats not already the case)

i will try and look at this on the weekend
Title: Re: MusicBee API
Post by: boroda on April 17, 2013, 08:06:52 PM
1. Please do so.
2. Currently I need it only for ReplayGainTrack and ReplayGainAlbum properties, but I think it would be useful also for LastPlayed, PlayCount and SkipCount properties.
3. OK

Thank you.

Title: Re: MusicBee API
Post by: quick_wango on June 16, 2013, 07:53:41 PM
I have a few questions:

1. Is it possible to provide more information on failed startup? My lyrics plugin has fails to enable every second time I disable and reenable it. The whole Initialise() has a try-catch block, but this still happens and I don't see why.

2. Are these *.config files required? my lyrics plugin kept crashing MusicBee without it.

3. Is there a documentation somewhere? it took my quite long to figure out that the mb_ in the name is required
Title: Re: MusicBee API
Post by: Steven on June 16, 2013, 08:21:57 PM
for 1 i guess that could be a MB bug but i would need your plugin to see whats going on
for 2, i dont think the file is essential as it tells the .NET environment which version to use but i think it can work it out itself. You should be using .NET4 client profile in your build settings. I have no idea why it would crash MB unless you were not using the .NET4 client profile build
for 3, only what you see in the notes on the forum topic and comments in the example program
Title: Re: MusicBee API
Post by: quick_wango on June 18, 2013, 11:08:49 PM
1. You can see my Code on GitHub: https://github.com/quickwango/LyricsReloaded

2. My fail, I used MB2 instead of MB2.1

3. This makes it quite hard to develop plugins. And the fact that we can't easily debug MusicBee itself makes it even harder.
Title: Re: MusicBee API
Post by: Steven on June 19, 2013, 07:39:50 PM
2. My fail, I used MB2 instead of MB2.1
i looks like you have an up-to-date MusicBeeInterface file but using the old method for loading the interface (i expect because thats how the old lyrics plugin did it). See the example file included with the download
replace:
                this.musicBee = (MusicBeeApiInterface)Marshal.PtrToStructure(apiPtr, typeof(MusicBeeApiInterface));
with:
            this.musicBee = new MusicBeeApiInterface();
            this.musicBee.Initialise(apiPtr);

that way it will not crash if you are using MB 2.0

for 1, having a quick look at the code you should move the initialisation logic to NotificationType.PluginStartup in ReceiveNotification(...)
the Initialise(...) function only gets called once whereas NotificationType.PluginStartup is called each time the plugin is enabled and wont be called if the plugin is disabled.
you should also call:
mbApiInterface.Setting_GetPersistentStoragePath()
to get the path for writing any settings/ working files.
Title: Re: MusicBee API
Post by: quick_wango on June 19, 2013, 07:43:39 PM
That was correct, however I didn't take the line from the Lyrics plugin^^ Seems like there are more plugins doing it wrong...
Title: Re: MusicBee API
Post by: Steven on June 19, 2013, 07:47:05 PM
i just added to the previous post in case you havent seen it.
Also as long as the interface definition file is an old one, it wont matter if the old initialisation method is used - it only matters if you are using a newer definition file
Title: Re: MusicBee API
Post by: quick_wango on June 19, 2013, 07:52:06 PM
But I'm not writing any files, just loading files a user might have placed in the sub directory.

Where is that persistent storage path going?
Title: Re: MusicBee API
Post by: Steven on June 19, 2013, 08:08:09 PM
i didnt look at your code closely so if you are reading a file only then thats fine.
If you are writing to files, the settings path will be same as for all musicbee settings related files and will depend on whether the user configures musicbee for portable mode - if not then the default windows application settings path is used
Title: Re: MusicBee API
Post by: quick_wango on June 19, 2013, 08:30:55 PM
These files are extensions to the plugin, so I think the location is appropriate.

What versions should I set to support 2.0?

also: have you seen http://getmusicbee.com/forum/index.php?topic=9971.0 ? that would make this easier^^
Title: Re: MusicBee API
Post by: Steven on June 19, 2013, 08:49:57 PM
Its only necessary to use a newer interface file if you need access to new functions which i dont think you do - any API interface updates are backwards compatible.
If you are to use the newer interface definition file and want the plugin to also work with MB 2.0, change:
            about.MinInterfaceVersion = MinInterfaceVersion;
            about.MinApiRevision = MinApiRevision;
to
            about.MinInterfaceVersion = 20;
            about.MinApiRevision = 25;
Title: Re: MusicBee API
Post by: quick_wango on June 19, 2013, 08:52:32 PM
You're suggestions broke the plugin. init() is not called anymore, so it seems like ReceiveNotification() is not being called
Title: Re: MusicBee API
Post by: Steven on June 20, 2013, 07:45:05 PM
the only reason i can think of is the plugin is disabled in the preferences
Title: Re: MusicBee API
Post by: quick_wango on June 20, 2013, 08:41:17 PM
it isn't
Title: Re: MusicBee API
Post by: Steven on June 20, 2013, 09:11:51 PM
i dont think i can help you any further with this then
Title: Re: MusicBee API
Post by: quick_wango on June 20, 2013, 09:18:49 PM
Oh you definitly can! Give more informations about the error. Either in the message box or in the log file. The plugin starts if I call init from Initialise(), but fails when I disable it and then try to re-enable it. Testing it with a unit test works fine.
Title: Re: MusicBee API
Post by: boroda on June 20, 2013, 09:24:30 PM
As far as I remember Initialise() is called only ones when plugin is initialized first time. Second time and so on only NotificationType.PluginStartup event is sent to plugin.
Title: Re: MusicBee API
Post by: quick_wango on June 20, 2013, 09:33:08 PM
There is the current code: https://github.com/quickwango/LyricsReloaded/blob/master/LyricsReloaded/LyricsReloaded.cs#L35

Maybe you see the problem.
Title: Re: MusicBee API
Post by: Steven on June 20, 2013, 09:43:46 PM
for 1, having a quick look at the code you should move the initialisation logic to NotificationType.PluginStartup in ReceiveNotification(...)
the Initialise(...) function only gets called once whereas NotificationType.PluginStartup is called each time the plugin is enabled and wont be called if the plugin is disabled.
I doubt there is any error - doing it the way you have done it means your initialise function wont be called the 2nd and subsequent re-enables.
Also i realise now what probably is the cause of the unexpected behavior is that the GetProviders() function can be called before before the ReceiveNotification function is called because of the way its implemented. I accept that undesirable behavior but there are too many plugins now to change it. My suggestion is to test if initialisation required on both. Please dont implement it where you have as that will slow down the load of MB and will be called even if the user has disabled the plugin.
Title: Re: MusicBee API
Post by: boroda on June 20, 2013, 09:45:13 PM
This wont work on vista/7 until you run MB as administrator:
Code
this.logger = new Logger(this.pluginDirectory + Path.DirectorySeparatorChar + this.name + ".log");
Use Setting_GetPersistentStoragePath() to get writable application directory.

At this moment I dont see anything else strange. The good decision is to use try-catch construction in Initialise() plugin function to write errors to log or display them on screen.
Title: Re: MusicBee API
Post by: quick_wango on June 20, 2013, 10:28:50 PM
This wont work on vista/7 until you run MB as administrator:
Code
this.logger = new Logger(this.pluginDirectory + Path.DirectorySeparatorChar + this.name + ".log");
Use Setting_GetPersistentStoragePath() to get writable application directory.

Fixed that, thanks for the notice. The first thing I do after installing windows is disabling the UAC.

@Steven: Just provide more information when a plugin fails to enable.
Title: Re: MusicBee API
Post by: boroda on June 20, 2013, 10:57:05 PM
@Steven: Just provide more information when a plugin fails to enable.
Use "try {...} catch (Exception e) {MessageBox.Show(e.Message)}" in the Initialise() function.
Title: Re: MusicBee API
Post by: quick_wango on June 20, 2013, 10:58:29 PM
Sure but still it would be better to have more information about the errors from the MusicBee side
Title: Re: MusicBee API
Post by: quick_wango on June 20, 2013, 11:55:32 PM
@Steven seems like you were wrong: Initialise(IntPtr) is called every time the plugin is enabled, and Close(PluginCloseReason) on every disable.
Title: Re: MusicBee API
Post by: slimmeke on July 01, 2013, 07:51:30 AM
Hey Guys.

I have a problem using the rate function of the MusicBee API. I can read the rating but can't write a new rating with the API.
I use fowolling code:

mbApiInterface.Library_SetFileTag(mbApiInterface.NowPlaying_GetFileUrl(), MetaDataType.Rating, "3.5");

Is this correct or is this the wrong way to do this?
Title: Re: MusicBee API
Post by: boroda on July 01, 2013, 08:44:45 AM
1. What are localizations of your MB & windows? Probably you need to call:

mbApiInterface.Library_SetFileTag(mbApiInterface.NowPlaying_GetFileUrl(), MetaDataType.Rating, "3,5");

2. Note that tag changes (writing changes to file) for now playing track can be delayed until next track is played.
Title: Re: MusicBee API
Post by: slimmeke on July 01, 2013, 08:48:00 AM
I have tested this but doesn't work  :-[.
Title: Re: MusicBee API
Post by: slimmeke on July 01, 2013, 01:35:26 PM
Can nobody help me with this rating problem?
This is the only bug that is in my next release of the Logitech Plugin.
When I fix this I can release it.
Title: Re: MusicBee API
Post by: Steven on July 01, 2013, 01:42:39 PM
can you explain what you mean by "but can't write a new rating with the API"
eg. what steps you are taking to verify that its not writing the tag.
tags are not written to a playing music file until playback has completed.

Also i expect what boroda74 says is true, and the decimal point needs to be localised (however i think the .NET tostring() does that automatically).
but you might try just using "3" or  using a 0-100 scale
Title: Re: MusicBee API
Post by: slimmeke on July 01, 2013, 02:49:29 PM
With "but can't write a new rating with the API" I mean that I can't change the rating value of the song.

I have test it with 5 0,5 and with the 100 scale. After I have runned the code, I go to the next song. So normally the rating has been saved.
But no rating has saved.

And the toString() function of a float use the . notation of a string :). But with replace you can change the "." to ",".

I have changed the source to:

        public void changeRating(float number)
        {
            String url = mbApiInterface.NowPlaying_GetFileUrl();
            string rating = number.ToString().Replace(".", ",");
            mbApiInterface.Library_SetFileTag(url, MetaDataType.Rating, rating);
        }

But doesn't work.
Title: Re: MusicBee API
Post by: Steven on July 01, 2013, 02:57:35 PM
as i said i think the .net tostring() function automatically localises the decimal value so you are only making things worse with .Replace(".", ",")
I think that is a red herring.

i will ask again, how are you verifying the rating is not saved?
Title: Re: MusicBee API
Post by: slimmeke on July 01, 2013, 03:07:34 PM
I verify it by changing the rating using my source.
Then I wait untill the song ends and after that I check if MusicBee sees any rating.
But without any result thus far.
Title: Re: MusicBee API
Post by: Steven on July 01, 2013, 03:18:21 PM
you need to call:
Library_CommitTagsToFile(url)

also i am still not clear how you are verifying the rating but as a guess from your response you are simply visually checking the main panel?
if that is the case, then you also need to call:
MB_RefreshPanels() so the main panel refreshes after you have made changes to any tags
Title: Re: MusicBee API
Post by: slimmeke on July 01, 2013, 03:21:57 PM
Tnx Steven that did the job.
Guys tnx for your time.
Have a nice day.
Title: Re: MusicBee API
Post by: Pako on July 04, 2013, 01:31:02 PM
I assumed that the API function Playlist_SetFiles(playlistUrl string, string[] filenames)
works the way that it overwrites the current contents of the playlist.
Now I've tried it and it is really so.
However, it is not very user friendly when I want to add some files.
So I have a feature request:
Can you please incorporate a new function Playlist_AddFiles(playlistUrl string, string[] filenames) ?
It would be ideal if the function automatically avoid duplication.
I got this requirement (add files to the playlist) in EventGhost plugin topic.

Thanks, Pako
Title: Re: MusicBee API
Post by: quick_wango on July 04, 2013, 07:52:10 PM
A question about lyrics: How does MusicBee differ between synchronized and not synchronized lyrics? GetProvider() knows what kind is preferred, but that is only a preference, how does MusicBee know of what kind the returned lyrics are?

As far as I can see, the old plugin doesn't even load synchronized lyrics.
Title: Re: MusicBee API
Post by: Steven on July 04, 2013, 08:21:05 PM
A question about lyrics: How does MusicBee differ between synchronized and not synchronized lyrics? GetProvider() knows what kind is preferred, but that is only a preference, how does MusicBee know of what kind the returned lyrics are?

As far as I can see, the old plugin doesn't even load synchronized lyrics.
disregard that parameter as it was never implemented. I recommend you return synchronised lyrics if there is a choice.
MB automatically detects and parses synchronised lyrics eg. somethimes they are available on the lrc123.com website for example.
Title: Re: MusicBee API
Post by: quick_wango on July 04, 2013, 10:52:31 PM
Ok, good to know
Title: Re: MusicBee API
Post by: Steven on July 07, 2013, 10:34:47 PM
Can you please incorporate a new function Playlist_AddFiles(playlistUrl string, string[] filenames) ?
It would be ideal if the function automatically avoid duplication.
that has been included in the next v2.2 update. I will make it available in a day or two
Title: Re: MusicBee API
Post by: Pako on July 08, 2013, 05:55:19 PM
Quote from: Steven
Quote from: Pako
Can you please incorporate a new function Playlist_AddFiles(playlistUrl string, string[] filenames) ?
It would be ideal if the function automatically avoid duplication.
that has been included in the next v2.2 update. I will make it available in a day or two
That's great, thank you very much.
I got it working even without the new function but I will change it (very happy).

Pako
Title: Re: MusicBee API
Post by: Pako on July 17, 2013, 03:44:42 PM
Can you please incorporate a new function Playlist_AddFiles(playlistUrl string, string[] filenames) ?
It would be ideal if the function automatically avoid duplication.
that has been included in the next v2.2 update. I will make it available in a day or two
According to the log file (which is part of the EventGhost plugin), I see that API revision = 31 and Interface version = 27.
But when I download a C# Source.zip file from http://getmusicbee.com/forum/index.php?topic=1972.0, so there are still older version.
Can you please update?
But maybe I misunderstood something, then I apologize.

Thanks, Pako
Title: Re: MusicBee API
Post by: e-motiv on July 18, 2013, 12:06:43 PM
Does anyone know: How do you tell MusicBee again your plugin failed to Initialise?

More detail:
I am writing a (storage) plugin and in the Initialise method I also check if all files and databases are accessible (even making backups). But when they don't check out I don't want the plugin to do anything anymore.  Since I cannot return false (PluginInfo expected) and since there is no failed-indication in the PluginInfo type either, I dunno how to go about this. I can do `mbAPI.MB_SendNotification(CallbackType.StorageFailed);`. 
Is that right and enough for a storage plugin? And what if my plugin was not a storage plugin (for the wiki)?
Title: Re: MusicBee API
Post by: Steven on July 19, 2013, 08:35:03 AM
you can review the subsonic plugin source code to see how a storage plugin should work:
http://www.mediafire.com/download/wh43lpnbzrpboaf/SubSonic.zip
Title: Track detail info string
Post by: Pako on August 04, 2013, 12:00:34 PM
I have one question, respectively a feature request.
It is possible (using a single API call) to obtain information string such as "128k MP3 Radio Stream" in the attached picture (from track details)?
If not, I think it would be very nice improvement.
(http://i44.tinypic.com/f9m3pu.png)

Thanks, Pako
Title: Re: MusicBee API
Post by: Steven on August 04, 2013, 12:23:09 PM
there isnt a direct way but you could construct it yourself using:
FilePropertyType.Kind
FilePropertyType.Bitrate
Title: Re: MusicBee API
Post by: Pako on August 04, 2013, 02:52:24 PM
there isnt a direct way but you could construct it yourself using:
FilePropertyType.Kind
FilePropertyType.Bitrate
Yes, in that case it would be relatively easy.
But if it's not a stream, it's a lot more complicated.
And I even have to first find out which case it is (stream or file).
So (given that MusicBee has always this string already constructed),
I thought it would be worthwhile to incorporate new functionality.
(http://i44.tinypic.com/rming8.png)

Thanks, Pako
Title: Re: MusicBee API
Post by: Pako on August 06, 2013, 10:48:11 AM
Maybe this gives the impression that I'm lazy write a bit of extra code.
This is not so. I just thought that such a feature would welcome more developers (not just me).
BTW - I'm working on a web UI for EventGhost plugin. I'm almost done.
Here you can see how it looks:
(http://i42.tinypic.com/2qdpnkh.png)
You can see that the "info string" I was able to build.
However, I stumbled upon the fact that the "FilePropertyType.Kind" returns something like "Stream", "MP3 Stream" and the like.
The word Radio I have to add yourself.
I have a question: It can be any other than Radio stream?
If yes, how I can know that it is just Radio ?

Pako
Title: Re: MusicBee API
Post by: Pako on August 07, 2013, 07:46:24 AM
there isnt a direct way but you could construct it yourself using:
FilePropertyType.Kind
FilePropertyType.Bitrate
So as I now realized it is not as easy as it seemed.
If you choose (in MusicBee) a language other than English, then it's a little confusing.

Thus behaves string FilePropertyType.Kind:
1) Radio Stream
MusicBee: correctly translated by language file
API: "Stream" (untranslated)
2) Web Stream
(http://i40.tinypic.com/mwcsqs.png)
MB: correctly translated by language file
API: incorrectly translated by language file (aka "audio file")

It is also a problem with the string "Unknown Bitrate".
MusicBee does not display it, but the API returns it (untranslated).
I'm actually glad it is untranslated, because in that case I can filter it.
If it was translated, is there any way to find the corresponding expression in the currently selected language?
Something like GetLocalisedString("Main.msg.UnBitrate#")  ?

I hope I wrote it clearly.
Pako
Title: Re: MusicBee API
Post by: boroda on August 07, 2013, 07:58:56 AM
Something like GetLocalisedString("Main.msg.UnBitrate#")  ?
+1
Title: Re: MusicBee API
Post by: Pako on August 07, 2013, 05:29:08 PM
I happened to noticed that also notifikacion window shows the wrong kind (untranslated):
(http://i44.tinypic.com/2zqasn8.png)

Pako
Title: Re: MusicBee API
Post by: Steven on August 13, 2013, 07:30:35 PM
I am not aware of any having developed an artwork retrieval plugin but i will mention that for v2.2 the API has changed so the expected result returned by the plugin is a web link rather than the bass64 string for the downloaded picture. This is for multi-threading changes being made to artwork retrieval.
If this does affect anyone, please let me know
Title: Re: MusicBee API
Post by: kelsos on August 13, 2013, 07:38:09 PM
Steven are you talking about this call
Code
 mbApiInterface.NowPlaying_GetDownloadedArtwork()
If yes I use the base64 at some points in the remote plugin but I could easily add some check for api version and handle it differently on the newer versions.
Title: Re: MusicBee API
Post by: Steven on August 13, 2013, 07:42:37 PM
no i am refering to a plugin dedicated to providing artwork to MusicBee. Yours retrieves artwork from MusicBee and is not impacted.
As a side note, i suggest you use the url based versions of the artwork retrieval as that should be more effecient (MB usually already has the artwork written to a temporary file so passing a link to that is much faster)
Title: Re: MusicBee API
Post by: boroda on August 31, 2013, 09:22:42 AM
What is the result of NowPlaying_GetDuration() and Player_GetPosition()? Number of seconds?
Title: Re: MusicBee API
Post by: kelsos on August 31, 2013, 09:29:54 AM
Number of milliseconds actually
Title: Re: MusicBee API
Post by: boroda on August 31, 2013, 11:35:42 AM
Thanks, kelsos
Title: Re: MusicBee API
Post by: boroda on August 31, 2013, 11:39:33 AM
Steven, is there any way of getting currently displayed rotating artist picture? NowPlaying_GetArtistPicture() returns only 1st artist picture from rotating ones.
Title: Re: MusicBee API
Post by: Steven on August 31, 2013, 12:23:51 PM
Steven, is there any way of getting currently displayed rotating artist picture? NowPlaying_GetArtistPicture() returns only 1st artist picture from rotating ones.
use NowPlaying_GetArtistPictureUrls(true, urls[]) to get them all the locally stored ones but there is no way to get the current active one
Title: Re: MusicBee API
Post by: boroda on August 31, 2013, 12:25:23 PM
Thanks.
Title: Re: MusicBee API
Post by: KissCool on November 17, 2013, 12:39:30 PM
Over time I will add APIs to stream music data, control GUI aspects so you can create new views or possibly entirely skin MusicBee.

Is it doable atm (I mean without any restriction or limitation)?
Title: SpeakBack plugin multi-track solution.
Post by: e-motiv on December 06, 2013, 04:33:18 PM
Steven,

I would like to work on teh issue my SpeakBack plugin's is experiencing wit multiple tracks changing at once.  The problem is nicely illustrated here with boroda's tag plugin (http://getmusicbee.com/forum/index.php?topic=4941.msg27414#msg27414), but it's also a more general problem. I don't agree with boroda that it's to differentiate between manual and automatic (since I experience it also as a problem when you select multiple tracks manually).

So, in 1 sentence, I think the right question would be:
"Is there a way to tell my plugin (at notification time) that there are more than 1 tracks that are changing tags ?"

As an alternate solution, I can try to make a timer that tries to pause my plugin when within, let's say, 300 ms another track is changed.  I have already a bit experimented with it, and I find it a bit too complex for the problem. Not only do I have to keep all the changes of every notification in memory for the first or last track (for when the timer times out, even more when it times out for just 1 track, when no issue), I am also wondering that those 300ms or more are never gonna be right, depending on delay from MB and other plugins themselves ánd the possible synchronous actions one of these might also make.
So, I'd really appreciate a simple "more-than-one-tracks-changing" variable somewhere (if you find the time for it or if it already exists in one form or another).
Title: Re: MusicBee API
Post by: Steven on December 17, 2013, 10:28:53 PM
the interface file on the first page has been updated with the support available in MusicBee v2.2
Title: Re: MusicBee API
Post by: Pako on December 19, 2013, 05:59:26 PM
I found, that in the new MusicBee API, some new Notification Types were introduced.
For example, ReplayGainChanged, FileDeleting, FileDeleted and ApplicationWindowChanged.
I try to use it in EventGhost plugin, but in vain. Nothing happens.
Can you please explain under what circumstances the mentioned events are triggered?
It is of course possible that I am doing something wrong. I apologize in that case.

Pako
Title: Re: MusicBee API
Post by: Steven on December 19, 2013, 10:19:10 PM
i think when i did file deleting/ deleted, it was only intended and is only implemented for use with device synchronisation for virtual device plugins so perhaps i should just remove it from the public interface file definition. Similarily ApplicationWindowChanged wasnt really intended for general use.

ReplayGainChanged should work though
Title: Re: MusicBee API
Post by: e-motiv on December 23, 2013, 11:52:59 AM
For the record:
FileDeleting / Deleted was also requested for my Ghost Track plugin here (http://getmusicbee.com/forum/index.php?topic=6085.msg60795#msg60795).  Since I released the latest version of the plugin nobody has asked the use of the delete-integration, so it might take a while before I integrate it, since I am working on improvement requests from other plugins* at the moment (when I find time for MB at all).  I did integrate the other things though! (Thanks again.)

* Also see earlier question in this thread about "multi-tracks changing on notification time"
Title: Re: MusicBee API
Post by: Pako on February 23, 2014, 01:04:38 PM
I have another feature request.
In my opinion there is missing a LibraryChanged event.
My "remote client" at startup retrieves the available playlists.
The remote user can then choose from these playlists.
However, if the "other" user (desktop GUI) opens another library,
the "remote client" does not know it. It is necessary to know it and update the list of available playlists.

Pako
Title: Re: MusicBee API
Post by: Steven on March 23, 2014, 11:12:45 PM
In my opinion there is missing a LibraryChanged event.
thats done for the next v2.4 update
it will be notified via
PluginNotifyType.LibrarySwitched = 29
Title: Re: MusicBee API
Post by: Pako on April 01, 2014, 10:46:44 AM
thats done for the next v2.4 update
it will be notified via
PluginNotifyType.LibrarySwitched = 29
I finally had a chance to try.
It works beautifully, now list (offer) of playlists always correspond to reality.
Thank you very much.

Pako
Title: Re: MusicBee API
Post by: bazinga on April 26, 2014, 03:33:23 PM
I think I have found 2 bugs in the API or in MusicBee.
When I do "mbApiInterface.Player_SetRepeat(RepeatMode.One);" MusicBee will set repeat to All instead of One.


Having exactly the same problem (but it returns None, not One as reported above)
Title: Re: MusicBee API
Post by: EpicCyndaquil on August 31, 2014, 08:15:42 AM
I'd like to enable changing of upmixing to 5.1 (http://getmusicbee.com/forum/index.php?topic=11492.msg82551#msg82551) via the API. Is this something you could add in the next update, Steven?
Title: Re: MusicBee API
Post by: Steven on September 27, 2014, 10:56:30 AM
the links in the first post have been updated with the API interface that is available with MusicBee 2.4
The new API functions are described in previous posts on this topic
Title: Re: MusicBee API
Post by: Pako on September 28, 2014, 03:48:33 PM
I found a typo in new MusicBee API / C#.
There is an expression "FiledAddedToLibrary = 30".
I think it has to be "FileAddedToLibrary = 30".

Pako
Title: Re: MusicBee API
Post by: Steven on September 28, 2014, 10:02:55 PM
its been corrected now - thanks for reporting this
Title: Re: MusicBee API
Post by: Cyano on December 23, 2014, 12:29:48 AM
So I'm experimenting and creating a new plugin, It needs the latest API Revision for "NowPlayingList_GetFileTags" method.

However with the latest API Revision,

The MB_AddMenuItem Delegate has been changed to: 

        public delegate System.Windows.Forms.ToolStripItem MB_AddMenuItemDelegate(string menuPath, string hotkeyDescription, EventHandler openHandler, EventHandler closeHandler);

So now it takes four parameters instead of three in the previous API, yet I can't seem to get it to work correctly.
Here is the code:
(http://i.imgur.com/OA6DqjD.png)

I can't see any problem with the method call, yet when I start MusicBee (Latest forum post version 2.5.5469),
I get this error: (http://i.imgur.com/xcAEbCp.png)

Now I'm not sure If this is an error on my part or a bug with the API, so I was wondering if anyone can tell me the problem. The adding menu item seems to work correctly with a lower version of the API.

---
And one last question,

        public delegate bool Library_GetFileTagsDelegate(string sourceFileUrl, MetaDataType[] fields, ref string[] results);

What exactly is the sourceFileUrl parameter asking for? I can understand that the second parameter wants the array of data/tag types I want and the results are passed by reference in the third parameter. If I want to query the MusicBee Library - what exactly do I need to pass to sourceFileUrl.

Thanks,
Cyano
Title: Re: MusicBee API
Post by: boroda on December 23, 2014, 06:01:15 AM
        public delegate bool Library_GetFileTagsDelegate(string sourceFileUrl, MetaDataType[] fields, ref string[] results);

What exactly is the sourceFileUrl parameter asking for? I can understand that the second parameter wants the array of data/tag types I want and the results are passed by reference in the third parameter. If I want to query the MusicBee Library - what exactly do I need to pass to sourceFileUrl.
sourceFileUrl is a file path, e.g C:\music\track1.mp3
Title: Re: MusicBee API
Post by: Steven on December 23, 2014, 07:30:18 AM
it looks like i messed up the following definitions - just change them manually and i will later update the official API file:
Code
        public delegate System.Windows.Forms.ToolStripItem MB_AddMenuItemDelegate(string menuPath, string hotkeyDescription, EventHandler handler);
        public delegate bool MB_AddTreeNodeDelegate(string treePath, string name, System.Drawing.Bitmap icon, EventHandler openHandler, EventHandler closeHandler);

the intention is i never break or change existing API calls
Title: Re: MusicBee API
Post by: Steven on January 13, 2015, 08:00:16 PM
the following API methods are available for the 2.5 series - the interface files and template are available in the first page

- retrieves information about the artwork associated with a music file
 bool Library_GetArtworkEx(string sourceFileUrl, int index, bool retrievePictureData, ref PictureLocations pictureLocations, ref string pictureUrl, ref byte[] imageData);

- updates the artwork associated with a music file
bool Library_SetArtworkEx(string sourceFileUrl, int index, byte[] imageData);

- gets information about the available visualisers and the current state
bool MB_GetVisualiserInformationDelegate(out string[] visualiserNames, out string defaultVisualiserName, out WindowState defaultState, out WindowState currentState);

- activates (or de-activates) a visualiser
bool MB_ShowVisualiserDelegate(string visualiserName, WindowState state);

- gets information about the available views for a plugin (currently only the theater mode plugin "mb_TheaterModePlugin.dll") and the current state
bool MB_GetPluginViewInformationDelegate(string pluginFilename, out string[] viewNames, out string defaultViewName, out WindowState defaultState, out WindowState currentState);

- activates (or de-activates) a plugin view
bool MB_ShowPluginViewDelegate(string pluginFilename, string viewName, WindowState state);

- gets the currently available output devices including any UPnP devices
bool Player_GetOutputDevicesDelegate(out string[] deviceNames, out string activeDeviceName);

- sets the active output device
bool Player_SetOutputDeviceDelegate(string deviceName);
Title: Re: MusicBee API
Post by: htsign on January 24, 2015, 03:37:06 PM
Hi, I have 3 questions.

First, how to write the path of context menu of lyrics display area?
I understood that
But I don't know lyrics area's one.

Next, is there a method to add lyrics to current song?
I wrote the code below instead of to relate lyrics and songs.
Code
private void SaveLyrics(string lyrics)
{
    string filePath = mbApiInterface.NowPlaying_GetFileUrl();
    string dirPath  = Path.GetDirectoryName(filePath);
    string fileName = Path.GetFileNameWithoutExtension(filePath) + ".lrc";

    string targetPath = Path.Combine(dirPath, fileName);
    try
    {
        using (var stream = new StreamWriter(targetPath, false))
        {
            stream.Write(lyrics);
            stream.Flush();
        }
        mbApiInterface.Library_SetFileTag(mbApiInterface.NowPlaying_GetFileUrl(), Plugin.MetaDataType.HasLyrics, "Y [synched]");
    }
    catch (IOException)
    {
        MessageBox.Show("Failed to write", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
I also doubt "NowPlaying_GetFileUrl" method with "MetaDataType.HasLyrics" is effective.
Anyway, I want to use it if there is a method to add lyrics.

Last, I hesitated this question is proper for this thread,
It seems the MusicBee Lyrics time line tag's parser takes "[01:23.45]" as not "[1:23.450]" but "[1:23.045]".
Some websites (e.g. Wikipedia) wrote the format is "[mm:ss.xx]".
I think it is original format. Let me know if it is wrong.

Thanks.
Title: Re: MusicBee API
Post by: leo_r on February 17, 2015, 11:35:35 PM
Hello!

I'm trying to create a playlist. The following code used to work (probably on 2.3.something) but now doesn't (using 2.5.5524)

Code
_mbApiInterface.Playlist_CreatePlaylist(playlistDir, playlist.Name, mbPlaylistSongFiles);

where playlistDir is a string to the playlist directory, playlist.Name is a string containing the name of the playlist I want to create and mbPlaylistSongFiles is a string array of paths to the songs I want to add.

Is this something that's changed in 2.5? I notice that the playlist file format changed, possibly in 2.3? Did this only work before then? I'm not actually sure what version it last worked with.

If this isn't the way to do it, how would I:

- Create a new playlist and add songs to it and
- Clear a playlist of songs and add re-add a new list to it

Thanks!
Title: Re: MusicBee API
Post by: Steven on February 18, 2015, 07:11:34 AM
working fine here. Can you expand upon "it doesnt work"
Title: Re: MusicBee API
Post by: leo_r on February 18, 2015, 10:47:26 AM
working fine here. Can you expand upon "it doesnt work"

Sorry - I really should have been more descriptive (or possibly not tried to ask questions so late at night).

Calling the function simply returns a null object. No exceptions are thrown, it's definitely being called (if I set a break point, it gets hit), but no playlist is created in MusicBee.

I'm not at home right now - I'll investigate further this evening. Would a malformed (or somehow not-acceptable-to-MusicBee) playlist path or name throw an exception, or just silently fail?
Title: Re: MusicBee API
Post by: leo_r on February 18, 2015, 08:20:42 PM
Further to my last post,
the exact function call which fails looks something like this:

Code

playlistDir = "C:\\Users\\Leo\\Music\\MusicBee\\Playlists\\"
playlist.Name = "Music I Like 2"
mbPlaylistSongFiles = {string[11]}

Where the string array is an array of things that look something like this:
[9] = "D:\\Music\\Music-15\\Criolo - Convoque Seu Buda\\10-Fio De Prumo (Padê Onã).mp3"

_mbApiInterface.Playlist_CreatePlaylist(playlistDir, playlist.Name, mbPlaylistSongFiles);

Typing this, I thought perhaps the issue was because of the weird characters in the above song, so I tried it again with a new playlist using songs which only have ASCII characters in the name - no difference. Function is called (breakpoint hit) but no playlist appears at the path in playlistDir.

Any thoughts? Could it be my installation (somehow?)
Title: Re: MusicBee API
Post by: Steven on February 18, 2015, 08:34:18 PM
use the logical name for the playlist folder
starting from the root folder = ""
so you would use "Classicial\1950s" for sub-folder "1950s" of folder "Classical"
Title: Re: MusicBee API
Post by: leo_r on February 18, 2015, 09:09:04 PM
Crucial missing information! Thanks. I thought the code I had used to work (in 2013), although it's possible I was wrong...
Title: Re: MusicBee API
Post by: Lepick on April 27, 2015, 11:20:57 PM

Hi Steven, I can't create a menu item under the 'Tools' menu as shown in the MB wiki tutorial.

Edited 4/30/15 - Never mind. I had started with an older API. Downloaded again today, works great.



Title: Re: MusicBee API
Post by: Steven on August 30, 2015, 04:16:52 PM
for MB v3, a change is being made to the API for creating embeded panels: MB_AddPanel where dock=PluginPanelDock.NowPlaying
in the current and earlier MB versions that API created a "UserControl" panel. In v3, the panel inherits from "Control" so that means if you depend on usercontrol properties such as scrollbar sizing/ positioning etc then it wont work.
I am not aware of anyone other than myself creating plugins using this API call but if you are and have concerns then let me know. There are a couple of approaches that can be taken.
The change is because the underlying controls MB uses/ supports has been substantially changed
Title: Re: MusicBee API
Post by: zorexx on December 23, 2015, 11:19:25 AM
Steven, may I know when will you release the MusicBee API for v3?
I am thinking that since v3 is just around the corner, I will target v3 for the next version of my plugin MusicBeeIPC, but I can't do so until I have the API for v3.
Title: Re: MusicBee API
Post by: Steven on December 23, 2015, 12:59:23 PM
V3 is focused on GUI changes and I dont anticipate making any API changes unless someone asks for something specific
Title: Re: MusicBee API
Post by: zorexx on December 23, 2015, 01:54:56 PM
I see, ok, I'll just use the API from this thread then. Thanks.
Title: Re: MusicBee API
Post by: MiDWaN on February 15, 2016, 10:55:21 AM
While working on a plugin I noticed a small typo, you might want to know:

- the method/function calls to "Initialise" should be named "Initialize" as is the correctly spelled word. :)

Though this might be a breaking change if everything refers to it by that name (including existing plugins for example).
Title: Re: MusicBee API
Post by: Steven on February 15, 2016, 12:50:15 PM
Initialise is the correct spelling and no plans to change it
Title: Re: MusicBee API
Post by: MiDWaN on February 15, 2016, 01:31:37 PM
Well, actually BOTH are correct if you look them up in dictionaries:
- Initialise is the British English version
- Initialize is the American English version

I just brought this up because from my experience it's usually called "Initialize" in documentation, code samples and production code.

No big deal really, just struck me as something that may had been missed.
Title: Re: MusicBee API
Post by: Pingaware on February 17, 2016, 01:58:10 PM
Steven is British, so he uses British spellings across his codebase.
Title: Re: MusicBee API
Post by: phred on February 17, 2016, 02:55:52 PM
Steven is British, so he uses British spellings across his codebase.
But the redesigned website, per Steven's request, will use US English rather than UK English.  As it gets closer to going live, I will be proofreading it to accommodate Steven's request.
Title: Re: MusicBee API
Post by: boroda on September 18, 2016, 04:46:30 AM
What is the format of 'imageData' in api call:

MbApiInterface.Library_SetArtworkEx(sourceFileUrl, 0, imageData);

i tried to convert Bitmap to byte[]:

Code
                    System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Bitmap));
                    Bitmap pic = (Bitmap)tc.ConvertFrom(Convert.FromBase64String(value));
                    byte[] imageData = (byte[])tc.ConvertTo(pic, typeof(byte[]));

                    return MbApiInterface.Library_SetArtworkEx(sourceFileUrl, 0, imageData);

but this doesn't do anything.
Title: Re: MusicBee API
Post by: Steven on September 18, 2016, 03:59:46 PM
its the raw data encoded as JPEG or PNG that you would find in an image file on your PC.
So if your starting point is an in-memory bitmap, then you could
- create a memoryStream
- bitmapImage.Save(memoryStream,Imaging.ImageFormat.Jpeg)
- memoryStream.ToArray() and pass that data
Title: Re: MusicBee API
Post by: boroda on September 19, 2016, 08:09:32 AM
thanks
Title: Re: MusicBee API
Post by: BioBiro on September 18, 2017, 04:06:57 AM
Hellooo~,

Could I request to have some delicious equaliser methods in the API, to get and set the bands? I know you can manually pull them out of Roaming/MusicBee/MusicBee3Settings.xml - <PlayerManualEqualiser> - but that's probably not going to be very forwards-compatible.

Mebbe something like dis':

Code
public Player_GetEqualiserBandsDelegate Player_GetEqualiserBands;
public Player_SetEqualiserBandsDelegate Player_SetEqualiserBands;

public delegate bool Player_GetEqualiserBands(ref float[] bands);
public delegate bool Player_SetEqualiserBands(float[] bands);
Title: Re: MusicBee API
Post by: e-motiv on September 25, 2017, 02:03:27 PM
Can anyone set me in the right direction to do something x seconds before the current tracks is about to stop, please?

What I specifically want to evade is, when setting a timer on the startplaying event, that it will run much too soon when meanwhile the user has paused or rewind or some other action that would desynchronize that timer. In other words, if a timer is necessary, is there a shorter or more clever way to do this without paying attention to all the possible events happening?
Thanks a lot!!

P.S. This is to finish my re-release of Speak Back plugin (https://getmusicbee.com/forum/index.php?topic=4941.0). I want her to remind the user to rate the current track a couple of seconds before the track ends.

Thanks again!
Title: Re: MusicBee API
Post by: Steven on September 25, 2017, 06:12:42 PM
query the duration of the track when the plugin receives a track change event and using a timer query the play position via the api every second for example
Title: Re: MusicBee API
Post by: e-motiv on September 25, 2017, 07:29:10 PM
OK. Thank you!
Title: Re: MusicBee API
Post by: e-motiv on October 22, 2017, 12:15:17 PM
Can anyone help me with a storage question, please? --> sqlite3.dll - How to target this library in .NET? (https://getmusicbee.com/forum/index.php?topic=23109)
I really want to choose the right choice before programming again. Thank you!
Title: Re: MusicBee API
Post by: slivlight on November 14, 2017, 01:45:41 PM
Just found out NowPlaying_GetSpectrumData can't return low to high frequency range on 3.1, it return centered frequency range now.
Anyway to fix it? :'(
Title: Re: MusicBee API
Post by: Steven on November 14, 2017, 06:13:39 PM
Just found out NowPlaying_GetSpectrumData can't return low to high frequency range on 3.1, it return centered frequency range now.
Anyway to fix it? :'(
https://getmusicbee.com/forum/index.php?topic=22822.0
Title: Re: MusicBee API
Post by: ucynml on November 24, 2017, 06:48:40 PM
Hello. I can't find the API for v3.1.
Can I use the API to set sort tags?
Title: Re: MusicBee API
Post by: Steven on November 25, 2017, 01:53:01 PM
Hello. I can't find the API for v3.1.
Can I use the API to set sort tags?
i have updated the first post and it includes the new sort tags
Title: Re: MusicBee API
Post by: ucynml on November 26, 2017, 11:35:58 AM
OK. Thanks!
Title: Re: MusicBee API
Post by: MiDWaN on March 07, 2018, 09:33:32 PM
Steven, I wanted to try using the provided "CreateBackgroundThread" call instead of firing off a Thread myself in my plugin.
I have two questions regarding that:

1) Is there a way to Abort the Thread if it's already started? Or is that handled automatically by MB in some cases? (e.g. when Closing?)
2) Is there a way to detect if a specific Thread has already been started, to avoid starting it again?

Also, could we please consolidate and improve the documentation on the various functions the API provides?
Having to read through 19 (currently) pages in a forum just to find out if there's any information about a specific function is not very practical.

In an ideal scenario either the documentation should be included in the source code itself (e.g. in the form of comments) or on a dedicated page somewhere, with usage examples if possible. I believe that would also help a lot with minimizing support questions regarding the API.

If there's already such a place with documentation and I've missed it, I apologize - could you please point me to it?
Title: Re: MusicBee API
Post by: cjoprey on March 29, 2018, 11:25:12 PM
Hi Steven,

Will the 3.1 API work with a 3.2 install, or should I wait for a new API?

Thanks!
Title: Re: MusicBee API
Post by: Steven on March 30, 2018, 07:35:41 AM
it should work fine and any future changes will be non-breaking
Title: Re: MusicBee API
Post by: cjoprey on April 02, 2018, 09:15:56 PM
Thanks Steven!
Title: Re: MusicBee API
Post by: neRok on April 22, 2018, 05:02:24 AM
Hi,
I've just submitted a new plugin, but there are some features I can't implement because there does not seem to be any suitable API methods for doing so. I've put a little info in some issues on my github repo, see https://github.com/neRok00/mb_SkipOverSong/issues/1 and https://github.com/neRok00/mb_SkipOverSong/issues/3. If you want any more info, I can give some here.
Title: Re: MusicBee API
Post by: Steven on April 22, 2018, 09:49:10 AM
I've approved the plugin. I cant see myself agreeing to either of the issues/requests
Title: Re: MusicBee API
Post by: neRok on April 23, 2018, 12:54:09 AM
For the tag one, if not a way to read any tag, why not a way to set a custom tag via api call from plugin?

Or even a way to set settings from a plugin? The plugin could send a dict of settings to change to the program, and the program can have a popup asking the user to accept the following changes (with a list of those changes).
Title: Re: MusicBee API
Post by: samlangten on October 24, 2018, 03:41:00 PM
Hello Steven,
I am trying to add internationalization support for my plugin, but I can not find API to get which languages user has set in MusicBee. Is there any way to access which languages user has set?
Title: Re: MusicBee API
Post by: Steven on October 24, 2018, 06:15:55 PM
MB_GetLocalisation(string id, string defaultText)
you can get the id's from the localisation file in the localisation topic
Title: Re: MusicBee API
Post by: samlangten on October 25, 2018, 05:25:33 AM
In fact I have some custom texts in my plugins which does not exist in MusicBee definitions. I want to get language setting in MusicBee and enable the localization files for my plugin.
Title: Re: MusicBee API
Post by: Steven on October 25, 2018, 07:36:59 AM
In fact I have some custom texts in my plugins which does not exist in MusicBee definitions. I want to get language setting in MusicBee and enable the localization files for my plugin.
you will need to have your own localisation implementation
dotNET provides a good infrastructure for that
Title: Re: MusicBee API
Post by: samlangten on October 25, 2018, 11:04:16 AM
In fact i have implemented localization by adding localization resx files and set Localizable property in Form class which is internal way of localization implementation in WinForm. I use System.Threading.Thread.CurrentUICulture.DisplayName to detect which language user is using, but what it returns seems depend on language setting of user's operation system instead of setting of MusicBee. So i want to get language setting of MusicBee to enable this internal way of implementation.
Title: Re: MusicBee API
Post by: Steven on October 25, 2018, 05:59:39 PM
I see, in that case there is no API call available. As a workaround, you could get a specific id, and compare it the expected value that the translator has set
Title: Re: MusicBee API
Post by: MiDWaN on February 15, 2019, 10:33:15 AM
Hi Steven,

Per several users' request, I'd like to implement a few extra features in the Subsonic plugin:
1) Save Playlists. There are currently GetPlaylists() and GetPlaylistFiles() which are already working, but is there a call I can use for saving them?
2) Get Podcasts. Is there a method that gets called for that through the API, that I can use to implement?
3) Save ratings. Again, is there a method that gets called that I can use to implement?

Thanks!
Title: Re: MusicBee API
Post by: boroda on February 15, 2019, 12:35:01 PM
for 3: use Library_SetFileTag(sourceFileUrl, MetaDataType.Rating, "xx"), where xx is in range 0-100 (%), i.e. Library_SetFileTag(sourceFileUrl, MetaDataType.Rating, "20") for 1 star.
Title: Re: MusicBee API
Post by: MiDWaN on February 15, 2019, 02:00:59 PM
for 3: use Library_SetFileTag(sourceFileUrl, MetaDataType.Rating, "xx"), where xx is in range 0-100 (%), i.e. Library_SetFileTag(sourceFileUrl, MetaDataType.Rating, "20") for 1 star.

Thanks for the reply, but I'm not sure how that would work?
I'm trying to save ratings from MusicBee back to Subsonic, through the plugin. To do that, MusicBee would need to have a call to a plugin method/function that I can then implement and send the information over.

I think what you mentioned above would do it the other way around, right?
Title: Re: MusicBee API
Post by: boroda on February 15, 2019, 02:24:27 PM
don't understand. do you need to receive a notification in subsonic plugin that rating is changed?
Title: Re: MusicBee API
Post by: MiDWaN on February 15, 2019, 02:29:40 PM
Close, I need to send a rating that was set in Musicbee over to the Subsonic server, through my plugin. So a notification might help, but I'd also need the actual track and new rating information.
So basically, I'm wondering if there's a method call that is triggered when a rating is set in Musicbee, which I can use through the API.

If there is, then it would be a matter of implementing that and sending the rating to the server (which is something I already know how to do).
Similar to let's say, clicking on a track and getting the Artwork fetched. There's "GetArtwork()" that is called when a user clicks on a track...
Title: Re: MusicBee API
Post by: boroda on February 15, 2019, 03:04:30 PM
misunderstood you first. use this:

Code
        // receive event notifications from MusicBee
        // you need to set about.ReceiveNotificationFlags = PlayerEvents to receive all notifications, and not just the startup event
        public void ReceiveNotification(string sourceFileUrl, NotificationType type)
        {
            // perform some action depending on the notification type
            switch (type)
            {
                case NotificationType.RatingChanged:
                //perform some action here
                break;
             }
          }

to get new rating use:
Code
Library_GetFileTag(sourceFileUrl, MetaDataType.Rating)
Title: Re: MusicBee API
Post by: MiDWaN on February 15, 2019, 04:20:22 PM
That seems to work, thanks!
Title: Re: MusicBee API
Post by: Steven on February 15, 2019, 06:31:55 PM
1) Save Playlists. There are currently GetPlaylists() and GetPlaylistFiles() which are already working, but is there a call I can use for saving them?
2) Get Podcasts. Is there a method that gets called for that through the API, that I can use to implement?
i will look at this is a couple of weeks time
Title: Re: MusicBee API
Post by: Steven on February 26, 2019, 07:43:03 PM
1) Save Playlists. There are currently GetPlaylists() and GetPlaylistFiles() which are already working, but is there a call I can use for saving them?
actually all the functions you need are there eg.
Playlist_CreatePlaylist(string folderName, string playlistName, string[] filenames)
and various other Playlist_xxxx functions to adjust the playlist files

2) Get Podcasts. Is there a method that gets called for that through the API, that I can use to implement?
can you tell me what you want to do with this? There is a hierarchical structure of subscriptions and episodes to consider
Title: Re: MusicBee API
Post by: MiDWaN on February 26, 2019, 08:23:58 PM
Hi Steven,

1) Thanks, I'll look into this further once I get a chance again

2) The actual request from the users was: if there is a way to listen to podcasts that I have on my libresonic server.

I know how to get them from the server, but I don't know how to integrate and make that work with MusicBee.
Title: Re: MusicBee API
Post by: Steven on February 26, 2019, 08:39:44 PM
2) The actual request from the users was: if there is a way to listen to podcasts that I have on my libresonic server.

I know how to get them from the server, but I don't know how to integrate and make that work with MusicBee.
Its not clear to me what you are asking for, especially with this statement "I know how to get them from the server, but I don't know how to integrate and make that work with MusicBee."

If you simply want to view and play the podcasts in the MusicBee library, you need to describe how you would want to navigate and select them as there is a subscription/ episode structure, and each subscription can have a huge number of files, many of which might only exist on the source website.
Title: Re: MusicBee API
Post by: MiDWaN on February 26, 2019, 08:54:03 PM
Sorry if I wasn't clear enough.
The Subsonic API supports a few methods we can call regarding Podcasts: http://www.subsonic.org/pages/api.jsp#getPodcasts

E.g. with "getPodcasts", we can retrieve all Podcast channels the server subscribes to, and (optionally) their episodes. An example of such a call can be found here:
http://www.subsonic.org/pages/inc/api/examples/podcasts_example_1.xml

Then there are calls to Refresh Podcasts, Download an Episode, etc.

I can implement all those calls in the Plugin, but we'd also need some way to use/trigger them from MusicBee's interface.

For example, "Podcast Directory" could be intercepted by plugins (if implemented) to call "getPodcasts" as in my example above. The results coming from the server could then be returned to MusicBee so that it can show them on the GUI (with the expected structure of course).
A "Refresh" on a Podcast channel could be implemented by plugins to call a refresh on the server side and return the results, and so on.

Hope this makes it a bit more clear?
Title: Re: MusicBee API
Post by: Steven on February 27, 2019, 07:56:37 PM
I not willing to do the podcast request as i think it will involve too much effort to implement for the benefit it provides
Title: Re: MusicBee API
Post by: MiDWaN on February 27, 2019, 10:06:46 PM
OK, thanks for the feedback.
I'll notify the users accordingly.
Title: Re: MusicBee API
Post by: MiDWaN on March 01, 2019, 11:11:57 PM
1) Save Playlists. There are currently GetPlaylists() and GetPlaylistFiles() which are already working, but is there a call I can use for saving them?
actually all the functions you need are there eg.
Playlist_CreatePlaylist(string folderName, string playlistName, string[] filenames)
and various other Playlist_xxxx functions to adjust the playlist files

Coming back to this again:
I can instantiate a Playlist_CreatePlaylist delegate, but isn't that used for Creating a new Playlist inside MusicBee? What I'm looking for is to get a notification when a MusicBee Playlist is created, so I can send the same playlist to Subsonic.
Is there any notification triggered when the user creates a new Playlist from MusicBee? I couldn't find one in the list of Notification Types at least.

Or is there another way that I'm missing to handle this?
Title: Re: MusicBee API
Post by: Steven on March 03, 2019, 06:32:36 PM
i will add these notifications to the API for the next v3.3 update
Code
    PlaylistCreated = 37
    PlaylistUpdated = 38
    PlaylistDeleted = 39
    PlaylistMoved = 40

this patch version has the change if you want to test it:
https://getmusicbee.com/patches/MusicBee33_Patched.zip
unzip and replace the existing musicbee files
Title: Re: MusicBee API
Post by: MiDWaN on March 03, 2019, 10:21:36 PM
i will add these notifications to the API for the next v3.3 update
Code
    PlaylistCreated = 37
    PlaylistUpdated = 38
    PlaylistDeleted = 39
    PlaylistMoved = 40

this patch version has the change if you want to test it:
https://getmusicbee.com/patches/MusicBee33_Patched.zip
unzip and replace the existing musicbee files

Thanks, I'll test it and get back with results as soon as I can.
Title: Re: MusicBee API
Post by: MiDWaN on March 04, 2019, 10:05:46 AM
@Steven
That seems to work, thank you. :)

Some things I noticed:
- When a new Playlist is Created in MusicBee, there are 3 notifications triggered in a sequence:
1) PlaylistCreated is triggered as soon as the new Playlist window opens up, it contains the default Playlist name ("Playlist").
2) PlaylistUpdated is triggered after the OK/Save button is pressed in the new Playlist window, still contains the default name (even if the user renamed it)
3) PlaylistMoved is triggered right after that, containing the final name given to the playlist.

For my purposes I can just listen for the 3rd one for "Create Playlist" because I need to get the name given to the playlist, so it's no big deal.
However, what's the point of the 2nd notification? That's a bit tricky because UpdatePlaylist could also mean that some tracks got added/removed, but if it's also triggered when a new playlist is created, you don't really know which scenario you've picked up...

Is that by design for some reason?
Title: Re: MusicBee API
Post by: Steven on March 04, 2019, 08:01:18 PM
There are multiple methods of creating a playlist, which can involve just one step. The way you choose involves 3 steps although that might not seem obvious to you as there are no files involved in each step for the method you chose.
I advise to check for all events and not assume PlaylistMoved as the last one
Title: Re: MusicBee API
Post by: exscape on March 10, 2019, 06:43:02 PM
I believe I've found a bug in the NowPlayingList_QueueFiles* functions. If the track path has a # sign in it, anything after is ignored by MusicBee (basically treated like a comment), so it can't find the file, and a (!) shows up in the Upcoming tracks list.
For example, if I call

Code
List<string> tracks;
...
tracks[0] = "file://D:\\Music\\Music\\Compilations\\Metal Hammer #200 A Tribute to Dimebag Darrell\\04 Walk.mp3";
mbApiInterface.NowPlayingList_QueueFilesNext(tracks.ToArray());

... the API returns true, but the track can't be played and is silently ignored if I skip to the next track.
If I double click the track, I get a confirmation dialog:
"The source file for track 'Metal Hammer ' could not be found. Would you like to locate it?
D:\Music\Music\Compilations\Metal Hammer

The same code has worked flawlessly for a month or so now, but always fails on paths containing #.
Title: Re: MusicBee API
Post by: Steven on March 10, 2019, 07:13:36 PM
It uses the .Net Uri.TryCreate function but I agree its not working now.
I havent changed anything so I guess a recent .NET update changed the behaviour
I suggest using this format:
Code
D:\Music\Music\Compilations\Metal Hammer #200 A Tribute to Dimebag Darrell\04 Walk.mp3
Title: Re: MusicBee API
Post by: Mugwump on June 05, 2019, 11:29:01 AM
Hi,

I noticed there is a release candidate for musicbee 3.3 which is compatible with dotnet framework 4.6.1. This version of dotnet framework is compatible with netstandard 2.0 assemblies (https://docs.microsoft.com/en-us/dotnet/standard/net-standard (https://docs.microsoft.com/en-us/dotnet/standard/net-standard)). Will music bee be able to work with plugins that are compiled as netstandard 2.0 class libraries?
Title: Re: MusicBee API
Post by: Steven on June 05, 2019, 06:23:44 PM
yes, and no need to recompile them using 4.6.1
Title: Re: MusicBee API
Post by: MiDWaN on June 08, 2019, 12:15:10 PM
Hi Steven,

I'm having trouble getting the Rating I've set on a track, in order to send it to the Subsonic server. It always seems to return "0" as rating, which is not what I've set.

Specifically, the call I'm using is this:

Code
var rating = Subsonic.GetFileTag(sourceFileUrl, Interfaces.Plugin.MetaDataType.Rating);

And GetFileTag is defined as such:
Code
public static Interfaces.Plugin.Library_GetFileTagDelegate GetFileTag;

A similar call to get the Starred/Love setting of a track, works as expected:
Code
var starred = Subsonic.GetFileTag(sourceFileUrl, Interfaces.Plugin.MetaDataType.RatingLove);

Is this a bug in MusicBee's Interface, or am I missing something?
Title: Re: MusicBee API
Post by: Steven on June 08, 2019, 01:38:49 PM
its best you use the rating scale 0-100, with no decimal separator
if you use 0-5, you might run into issues with the decimal separator symbol for half ratings
looking at the code it looks to me like MB returns the rating on the 0-5 scale
Title: Re: MusicBee API
Post by: MiDWaN on June 08, 2019, 04:07:34 PM
I wouldn't have a problem either way (Subsonic server uses 0-5 internally, with 0 being no rating set), but I only get "0" back from MB in my tests.

I've hooked that GetFileTag to the TagsChanged notification type, and it does trigger when I change a rating on a track in MB. But regardless what rating I set it to, I always get back "0" from the GetFileTag() call.

The RatingLove tag instead, gives me the correct value. I have that one in the same location as well.

Here's a more complete code listing in case it helps:

Code
public void ReceiveNotification(string sourceFileUrl, Interfaces.Plugin.NotificationType type)
{
    switch (type)
                {

                  ...
                    case Interfaces.Plugin.NotificationType.TagsChanged:
                        var rating = Subsonic.GetFileTag(sourceFileUrl, Interfaces.Plugin.MetaDataType.Rating);
                        var starred = Subsonic.GetFileTag(sourceFileUrl, Interfaces.Plugin.MetaDataType.RatingLove);
                  ...

From the above code, "rating" is always "0" when retrieved but "starred" gets the proper expected value when set.
Title: Re: MusicBee API
Post by: Steven on June 08, 2019, 04:41:15 PM
you should listen for:
            RatingChanging = 15,
            RatingChanged = 12,

if you still cant get it to work i wont be able to help further
Title: Re: MusicBee API
Post by: MiDWaN on June 08, 2019, 08:54:56 PM
Even if I explicitly listen for those events instead (RatingChanging, RatingChanged), when I call GetFileTag() from them for the specific source file, the rating that comes back is always "0" (as a string, so it's not a conversion problem).

Is GetFileTag the right way to get the Rating?
Title: Re: MusicBee API
Post by: NighTeagle on August 02, 2019, 12:09:07 PM
Is it possible that the project file is missing from the VB.Net source ?
I've been trying to add a VB project to the solution, but so far I can't get it to work.

The C# source does have a project file.
Title: Re: MusicBee API
Post by: Steven on August 03, 2019, 09:01:25 AM
woops - added it now:
http://www.mediafire.com/file/v9207ekc5h8xojx/VB_Source3.1.zip/file
Title: Re: MusicBee API
Post by: NighTeagle on August 05, 2019, 11:50:17 AM
Oh everything makes much more sense now.
Thanks for the quick fix!
Title: Re: MusicBee API
Post by: psychoadept on November 23, 2019, 01:27:46 AM
I was trying to finally get myself set up with this in Visual Studio, and noticed on the main downloads page that it's still the 3.0 API. Should that be updated?

Update: unrelated, but whoo-boy! I accidentally downloaded the VB version of it at first and I was freaking out a little. Got C# now, much better. I'm impressed you can maintain both, Steven.
Title: Re: MusicBee API
Post by: Steven on November 23, 2019, 03:22:20 PM
I was trying to finally get myself set up with this in Visual Studio, and noticed on the main downloads page that it's still the 3.0 API. Should that be updated?
that is an old link - where did you get it from?
Title: Re: MusicBee API
Post by: psychoadept on November 23, 2019, 03:36:06 PM
Here? https://getmusicbee.com/help/api/

Although I realize now it says "for MusicBee 3.0" not API version 3.0, so maybe it's fine. I downloaded the file from this thread to be sure (that's where I grabbed the wrong one).

I was totally gonna text myself VB if I had to, but I'm glad I don't.
Title: Re: MusicBee API
Post by: karaluh on April 16, 2020, 10:11:56 PM
I'm writing a ListenBrainz scrobbler plugin, is it possible to extend the NowPlaying_GetFileTag method to get MBIDs?
Title: Re: MusicBee API
Post by: boroda on May 23, 2020, 05:49:43 AM
set up mbid as custom tag.
Title: Re: MusicBee API
Post by: Azthenix on June 25, 2020, 12:00:54 AM
Player_SetRepeat(RepeatMode.One) doesn't work. It only toggles between All and None mode.
Title: Re: MusicBee API
Post by: Steven on June 25, 2020, 11:34:51 AM
this should fix the issue. I will include in the next official release which should be soon

https://getmusicbee.com/patches/MusicBee33_Patched.zip
unzip and replace the existing musicbee application files
Title: Re: MusicBee API
Post by: Azthenix on June 25, 2020, 04:17:05 PM
this should fix the issue. I will include in the next official release which should be soon

https://getmusicbee.com/patches/MusicBee33_Patched.zip
unzip and replace the existing musicbee application files

Yes, it now works. Thank you so much.
Title: Re: MusicBee API
Post by: Mugwump on October 29, 2020, 07:28:01 PM
I've called
Code
MB_SetBackgroundTaskMessage
from inside my task callback thread but I cannot see where this is supposed to be shown on the taskbar?

With the background tasks is it possible to set the taskbar progress indicator using the MB API?
Title: Re: MusicBee API
Post by: Steven on November 01, 2020, 12:45:06 AM
With the background tasks is it possible to set the taskbar progress indicator using the MB API?
The api call updates the text on the MusicBee status bar, not the windows taskbar. I do recall though that if the player controls panel shows a wavebar, the text for the playing track takes precedence.

You should be able to update the taskbar progress by getting a handle to the musicbee application window using: MB_GetWindowHandle()
and using that handle there are windows api calls to update the windows taskbar progress. This is some code:
Code
private enum TBATFLAG
{
    TBATF_USEMDITHUMBNAIL = 0x1,
    TBATF_USEMDILIVEPREVIEW = 0x2
}

private enum TBPFLAG
{
    TBPF_NOPROGRESS = 0,
    TBPF_INDETERMINATE = 0x1,
    TBPF_NORMAL = 0x2,
    TBPF_ERROR = 0x4,
    TBPF_PAUSED = 0x8
}

private enum THBMASK
{
    THB_BITMAP = 0x1,
    THB_ICON = 0x2,
    THB_TOOLTIP = 0x4,
    THB_FLAGS = 0x8
}

private enum THBFLAGS
{
    THBF_ENABLED = 0,
    THBF_DISABLED = 0x1,
    THBF_DISMISSONCLICK = 0x2,
    THBF_NOBACKGROUND = 0x4,
    THBF_HIDDEN = 0x8
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct THUMBBUTTON
{
    [MarshalAs(UnmanagedType.U4)]
    public THBMASK dwMask;
    public uint iId;
    public uint iBitmap;
    public IntPtr hIcon;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string szTip;
    [MarshalAs(UnmanagedType.U4)]
    public THBFLAGS dwFlags;
}

[StructLayout(LayoutKind.Sequential)]
private struct NATIVERECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

[ComImport()]
[Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface ITaskbarList3
{
    [PreserveSig()]
    void HrInit();
    [PreserveSig()]
    void AddTab(IntPtr hwnd);
    [PreserveSig()]
    void DeleteTab(IntPtr hwnd);
    [PreserveSig()]
    void ActivateTab(IntPtr hwnd);
    [PreserveSig()]
    void SetActiveAlt(IntPtr hwnd);
    [PreserveSig()]
    void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen);
    void SetProgressValue(IntPtr hwnd, UInt64 ullCompleted, UInt64 ullTotal);
    void SetProgressState(IntPtr hwnd, TBPFLAG tbpFlags);
    void RegisterTab(IntPtr hwndTab, IntPtr hwndMDI);
    void UnregisterTab(IntPtr hwndTab);
    void SetTabOrder(IntPtr hwndTab, IntPtr hwndInsertBefore);
    void SetTabActive(IntPtr hwndTab, IntPtr hwndMDI, TBATFLAG tbatFlags);
    void ThumbBarAddButtons(IntPtr hwnd, uint cButtons, [MarshalAs(UnmanagedType.LPArray)] THUMBBUTTON[] pButtons);
    void ThumbBarUpdateButtons(IntPtr hwnd, uint cButtons, [MarshalAs(UnmanagedType.LPArray)] THUMBBUTTON[] pButtons);
    void ThumbBarSetImageList(IntPtr hwnd, IntPtr himl);
    void SetOverlayIcon(IntPtr hwnd, IntPtr hIcon, [MarshalAs(UnmanagedType.LPWStr)] string pszDescription);
    void SetThumbnailToolTip(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszTip);
    void SetThumbnailClip(IntPtr hwnd, ref NATIVERECT prcClip);
}

[Guid("56FDF344-FD6D-11d0-958A-006097C9A090")]
[ClassInterface(ClassInterfaceType.None)]
[ComImport()]
private class TaskbarListClass
{
}


    taskBarInterface = (ITaskbarList3)new TaskbarListClass();
    taskBarInterface.HrInit();

Title: Re: MusicBee API
Post by: dandepeched on February 15, 2021, 02:34:48 PM
Hi @Steven, I'm developing Remote application for iOS and I'm trying to use API to reorder Now Playing list.
But I cannot make it to work properly if Shuffle is enabled.

I tried to get track index
Code
NowPlayingList_GetCurrentIndex();
to move track to different index
Code
NowPlayingList_MoveFilesDelegate(int[] fromIndices, int toIndex);
(so the indexes has looked like "from":4014,"to":5712)

After this action list got re-shuffled instead of moving 1 item.

I also tried to use actual displayed position by querying NowPlaying files
Code
NowPlayingList_QueryFiles(null);
(so position looked like "from":2,"to":3)
It gives me the same result - list got re-shuffled.

Maybe I'm using it wrong? Will appreciate any advice.
Title: Re: MusicBee API
Post by: Steven on February 20, 2021, 09:38:06 AM
NowPlayingList_MoveFiles uses the same internal functions as manually drag/dropping files, however i do see one inconsistency.
Does this version work better?
https://getmusicbee.com/patches/MusicBee34_Patched.zip

If not, are you saying that you are comparing NowPlayingList_QueryFiles(null) before and after the operation that its shuffled? If so, I dont see how that would have been case so could you explain how you determined the list is re-shuffled?
Title: Re: MusicBee API
Post by: dandepeched on February 20, 2021, 12:06:30 PM
NowPlayingList_MoveFiles uses the same internal functions as manually drag/dropping files, however i do see one inconsistency.
Does this version work better?
https://getmusicbee.com/patches/MusicBee34_Patched.zip

Unfortunately no, same result  :(
By the way _api.NowPlayingList_RemoveAt(index) works fine, which makes me think that retrieved indexes are correct.
Also NowPlayingList_MoveFiles works fine when Shuffle is off (so the indexes go in natural order)

If not, are you saying that you are comparing NowPlayingList_QueryFiles(null) before and after the operation that its shuffled? If so, I dont see how that would have been case so could you explain how you determined the list is re-shuffled?

I'm not comparing it in code, I see it re-shuffled in player. I think it makes sense to share the code:
1) To get Now Playing list and appropriate track indexes:
Code
public void RequestNowPlayingListOrdered(string clientId, int offset = 0, int limit = 100)
        {
            _api.NowPlayingList_QueryFiles(null);

            var tracks = new List<NowPlaying>();
            var position = 1;
            var itemIndex = _api.NowPlayingList_GetCurrentIndex();
            while (position <= limit)
            {
                var trackPath = _api.NowPlayingList_GetListFileUrl(itemIndex);

                var track = getFileMetadata(trackPath, itemIndex);

                tracks.Add(track);
                itemIndex = _api.NowPlayingList_GetNextIndex(position);
                position++;
            }

            sendDataToClient(clientId, tracks);
        }
2) To change order of Now Playing list:
Code
public void RequestNowPlayingMove(string clientId, int from, int to)
        {
            bool result;
            int[] aFrom = {from};
            int dIn;
            if (from > to)
            {
                dIn = to - 1;
            }
            else
            {
                dIn = to;
            }
            result = _api.NowPlayingList_MoveFiles(aFrom, dIn);

            sendDataToClient(clientId, result);
        }
Title: Re: MusicBee API
Post by: Steven on February 21, 2021, 08:11:30 AM
Actually there is a flaw in the internal functions for manual file drag/drop that is causing the issue you having. I will look to fix it over the next few days
Title: Re: MusicBee API
Post by: Steven on February 22, 2021, 07:54:56 AM
https://getmusicbee.com/patches/MusicBee34_Patched.zip
Title: Re: MusicBee API
Post by: dandepeched on March 02, 2021, 12:14:48 PM
https://getmusicbee.com/patches/MusicBee34_Patched.zip

This version definitely better, but still inconsistent.
List is not reshuffled anymore, but unexpected tracks appear instead of moving track. Sometimes it works as expected, but mainly not.
Here are some consecutive observations:
Code
Initial list - "position":3939,"position":115,"position":178,"position":3693,"position":2517...
3939 is Now Playing track, so I'm not touching it.

Move "from":178,"to":115
Result "position":3939,"position":116,"position":114,"position":3693,"position":2517...
115 properly moved to 116, but 114 is a new track instead of 178 (from the same album as 116). 117 is not shown anymore.

Move "from":3693,"to":114
"position":3939,"position":117,"position":115,"position":113,"position":2518...
116 moved to 117, 114 moved to 115, but 113 is a new track instead of 3693 (from the same album as 114 and 116), 2517 moved to 2518

Move in different direction "from":117,"to":115
"position":3939,"position":114,"position":116,"position":113,"position":2518...
Where previous 3693 appears back as 114 (instead of 115), 117 moved to 116

Move "from":114,"to":116
"position":3939,"position":115,"position":116,"position":113,"position":2518...
Action consistent - everything worked as expected! (116->115, 114->116)

Let me know if any additional information is needed
Title: Re: MusicBee API
Post by: Steven on March 03, 2021, 10:00:30 AM
that will teach me for making last minute optimisations. It better work this time:
https://getmusicbee.com/patches/MusicBee34_Patched.zip
Title: Re: MusicBee API
Post by: dandepeched on March 03, 2021, 10:18:43 AM
that will teach me for making last minute optimisations.

A temptation for any developer  ::)

https://getmusicbee.com/patches/MusicBee34_Patched.zip

Unfortunately it is still inconsistent :(
Behavior is similar to my last observations - track from non-shuffled order (same album) appears instead of track I'm trying to move (with Now Playing shuffled order).
Title: Re: MusicBee API
Post by: Steven on March 04, 2021, 08:31:33 AM
When using the API calls, the only issue i can reproduce is a minor GUI issue where MB displays the playing icon against the wrong file but is fine for subsequent files. That only happens when moving files via the API and not manual drag/drop.
Using your RequestNowPlayingListOrdered() function the list always looks fine to me after trying various move operations. I dont think I will spend more time on this.
Just in case its a misunderstanding of what NowPlayingList_MoveFiles() does - it changes the physical ordering of files in the playing tracks list which means that MB internally adjusts the indices of the upcoming tracks to match the new physical ordering of the files but it is not moving files up or down the next in sequence order
Title: Re: MusicBee API
Post by: dandepeched on March 04, 2021, 09:02:37 AM
When using the API calls, the only issue i can reproduce is a minor GUI issue where MB displays the playing icon against the wrong file but is fine for subsequent files. That only happens when moving files via the API and not manual drag/drop.
Using your RequestNowPlayingListOrdered() function the list always looks fine to me after trying various move operations. I dont think I will spend more time on this.
Just in case its a misunderstanding of what NowPlayingList_MoveFiles() does - it changes the physical ordering of files in the playing tracks list which means that MB internally adjusts the indices of the upcoming tracks to match the new physical ordering of the files but it is not moving files up or down the next in sequence order

Hi Steven, just to clarify your statement, let me try to layout a scenario:
1) I have a playlist sorted by Album Artist/Year/Album
2) I start playback of this list non-shuffled and Now Playing indices are 0,1,2,3...
3) I press Shuffle and now indices are 0,2355,2367,2259...
4) I want to change Now Playing list order, so that next 2 tracks exchange their positions (2355 <-> 2367)
5) Currently I'm trying to call either _api.NowPlayingList_MoveFiles(2355, 2367); or  _api.NowPlayingList_MoveFiles(2367, 2354);

Is it correct approach? If not, how to satisfy the intention from step 4?
Title: Re: MusicBee API
Post by: Steven on March 04, 2021, 09:22:00 AM
Thats an example of what i am saying. There is no api call to move files ordering within the shuffle list, just move files physical displayed ordering
Title: Re: MusicBee API
Post by: dandepeched on March 04, 2021, 10:11:36 AM
Thats an example of what i am saying. There is no api call to move files ordering within the shuffle list, just move files physical displayed ordering

I would love to see such API to mirror the drag and drop functionality of MB player. Or at least some workaround API like "NowPlayingList_QueueAtPostion".
Also one more missing API which is requested by users is access to History list.

It would be great if you can consider this 2 items to be added in some future!
Title: Re: MusicBee API
Post by: Steven on March 04, 2021, 10:23:22 AM
It does mirror the drag/drop functionality. When you have the shuffle button enabled and showing Playing Tracks, drag/dropping just changes the displayed order. The shuffle order is unchanged. Thats what the api does.
I am happy to add something for v3.5
Title: Re: MusicBee API
Post by: dandepeched on March 04, 2021, 10:30:58 AM
It does mirror the drag/drop functionality. When you have the shuffle button enabled and showing Playing Tracks, drag/dropping just changes the displayed order. The shuffle order is unchanged. Thats what the api does.
I am happy to add something for v3.5

Sorry, I still cannot understand how it works :)
When I use MusicBee player I see following when Shuffle is enabled. After drag and drop displayed list is always re-ordered as expected:
https://imgur.com/a/b17YLS8 (https://imgur.com/a/b17YLS8)

But I cannot mirror that behavior with API as I explained in my previous posts. When I try to "move" with indexes, sometimes unexpected files appears in the displayed list.
What am I doing wrong?
Title: Re: MusicBee API
Post by: dandepeched on March 04, 2021, 10:48:58 AM
I made a short video which shows incorrect displayed order - https://drive.google.com/file/d/11YcLtTQO2KDk4mmojB3vq6AsFm0inWNZ/view?usp=sharing
Steps:
1) Select Play Shuffled for some playlist
2) Go to Now Playing tab to observe the API call result
3) With the API move "The Creation" track to the previous position (which is "Graduation of the Soul")
4) Observe that "The Creation" track disappears and "The Land of Pan" track appears instead of it (which has a neighbor index for "Graduation of the Soul")

Funny thing that sometimes re-order works as expected. As a next step I moved "Graduation of the Soul" to the previous position ("Horizon") and this time it worked as expected!

I still believe there is a bug with the API. Please try to reproduce it by moving same 2 files in different direction few times (move down, than move back up, vice versa, etc)
Title: Re: MusicBee API
Post by: Steven on March 06, 2021, 09:27:11 AM
You are showing the "upcoming tracks" which is the order within the shuffle list ie. the order that tracks will play on completion of each track or clicking the next track button. Thats not the same as the order of the tracks on  the "playing tracks" list eg. you might have tracks 1,2,3,4 from an album on the playing tracks list (switch the view to "playing tracks" and it will show the tracks in order 1,2,3,4) but when shuffle is enabled the tracks might play in order 3,1,2,4. In the upcoming tracks view the display order will be 3,1,2,4
The api is moving the order of tracks in the playing tracks list, not the sequence within the shuffle order.

Having said that, there might be a display bug in the upcoming tracks view as i would expect the moving tracks with api call would have no effect on the tracks displayed in that view.
But it doesnt change that the api is not moving tracks in the shuffle order

Title: Re: MusicBee API
Post by: dandepeched on March 06, 2021, 09:34:39 AM
You are showing the "upcoming tracks" which is the order within the shuffle list

Thanks for explanation! So is there an API to mirror drag and drop action for "Upcoming Tracks" list?
If not, than it would be great to add it in v3.5 :) In my opinion this is important, as it seems to be the only way to edit shuffled order.
Title: query in the library
Post by: Kafka on March 14, 2021, 06:36:04 PM
Hi Steven.
I've trouble querying and getting files in the library,is it right to get by using Library_QueryFilesEx*?And what the format of parameter "query"?
Title: Re: MusicBee API
Post by: Steven on March 14, 2021, 09:49:55 PM
its the same xml format used to store auto-playlists, so to make it easy create an auto-playlist in MB with the appropriate query and use the xml from the saved file as the basis to build queries
Title: Re: MusicBee API
Post by: Kafka on March 15, 2021, 10:05:37 AM
Unfortunately,I dont konw why it gets all the files in the library but not the one I want.Here is the code:
Code
            StringBuilder query = new StringBuilder();
            query.Append("<SmartPlaylist");
            query.Append("<Source Type=\"1\">");
            query.Append(" <Description />");
            query.Append(" <Conditions CombineMethod=\"All\">");
            query.Append(" <Condition Field=\"None\" Comparison=\"Is \" Value=\"Someone Like You\" />");
            query.Append(" </Conditions>");
            query.Append("</Source>");
            query.Append("</SmartPlaylist>");
            pApi.Library_QueryFilesEx(query.ToString().Trim() + "", out var results);
Title: Re: MusicBee API
Post by: Steven on March 15, 2021, 10:26:48 AM
<SmartPlaylist is missing the closing bracket
Title: Re: MusicBee API
Post by: Kafka on March 15, 2021, 10:31:50 AM
......sorry,but still the same.
Title: Re: MusicBee API
Post by: Kafka on March 15, 2021, 04:17:48 PM
Library_QueryFilesEx* can't get any files with the query below
Code
string query = " <SmartPlaylist>\n"
            +"<Source Type=\"1\">\n"
            + "<Conditions CombineMethod=\"All\"> \n"
            + "<Condition Field=\"Title\" Comparison=\"Is\" Value=\"Mysteria Tale\" />\n"
            + "</Conditions>\n"
            + "</Source>\n"
            + "</SmartPlaylist>\n";
However,it can get all files in the library with the query below
Code
StringBuilder query = new StringBuilder();
            query.Append("<SmartPlaylist>\n");
            query.Append("<Source Type=\"1\">\n");
            query.Append("<Conditions CombineMethod=\"All\">\n");
            query.Append("<Condition Field=\"Title\" Comparison=\"Is \" Value=\"Mysteria Tale\" />\n");
            query.Append("</Conditions>\n");
            query.Append("</Source>\n");
            query.Append("</SmartPlaylist>\n");
What's more ,it alse gets all files in the library  with such query
Code
StringBuilder query = new StringBuilder();
            query.Append("<SmartPlaylist>\n");
I am puzzled.
Title: Re: MusicBee API
Post by: dandepeched on March 16, 2021, 10:44:46 AM
I am puzzled.

Hi Kafka! Maybe I can help you.
To query all files from library you can do the following:
Code
string[] songsList = null;
_api.Library_QueryFilesEx(null, ref songsList);
To build a query you can use "Library_QueryFiles" method:
Code
string searchText= "SomeTitleToSearch"
_api.Library_QueryFiles(XmlFilter(new[] {"Title"}, searchText, false);
Here is the XmlFilter implementation, it may not cover all the cases, but will help you to get the idea:
Code
       private static string XmlFilter(string[] tags, string query, bool isStrict,
            SearchSource source = SearchSource.None)
        {
            short src;
            if (source != SearchSource.None)
            {
                src = (short) source;
            }
            else
            {
                var userDefaults = UserSettings.Instance.Source != SearchSource.None;
                src = (short)
                (userDefaults
                    ? UserSettings.Instance.Source
                    : SearchSource.Library);
            }


            var filter = new XElement("Source",
                new XAttribute("Type", src));

            var conditions = new XElement("Conditions",
                new XAttribute("CombineMethod", "Any"));
            foreach (var tag in tags)
            {
                var condition = new XElement("Condition",
                    new XAttribute("Field", tag),
                    new XAttribute("Comparison", isStrict ? "Is" : "Contains"),
                    new XAttribute("Value", query));
                conditions.Add(condition);
            }
            filter.Add(conditions);

            return filter.ToString();
        }
Title: Re: MusicBee API
Post by: dandepeched on March 16, 2021, 11:07:23 AM
Hi Steven, I think I have found 1 more issue in the API.
It appears for the Upcoming Tracks list when using _api.NowPlayingList_QueueFilesNext(songsArray); and then _api.NowPlayingList_QueryFiles(null); while Shuffle is On.

Steps to reproduce:
1) Play some playlist with Shuffle ON.
2) Call _api.NowPlayingList_QueryFiles(null); and go though list with _api.NowPlayingList_GetNextIndex(offset); to receive Upcoming Tracks list
3) Received list is identical to the one displayed in MusicBee player
4) Call _api.NowPlayingList_QueueFilesNext(songsArray); to queue some file.
5) Observe that Upcoming Tracks list is updated properly in MusicBee player
6) Use API from step 2 to receive Upcoming Tracks list
7) Received list is NOT identical to the one displayed in the player - currently playing track is displayed as "queued" instead of selected track
8 ) Repeat steps 3-6 for another track
9) Received list is NOT identical to the one displayed in the player - queued track from step 4 is now displayed in proper position, but currently playing track is displayed as "queued" instead of recently queued track from step 8
10) Press Next and use API from step 2 to receive Upcoming Tracks list
11) Proper track from step 4 is playing now
12) Received list is NOT identical to the one displayed in the player - currently playing track is displayed as "queued" instead of selected track from step 8

Here is the code I use to get Upcoming Tracks list:
Code
public void RequestNowPlayingListOrdered(string clientId, int offset = 0, int limit = 100)
        {
            _api.NowPlayingList_QueryFiles(null);

            var tracks = new List<NowPlaying>();
            var position = 1;
            var itemIndex = _api.NowPlayingList_GetCurrentIndex();
            while (position <= limit)
            {
                var trackPath = _api.NowPlayingList_GetListFileUrl(itemIndex);

                var track = getFileMetadata(trackPath, itemIndex);

                tracks.Add(track);
                itemIndex = _api.NowPlayingList_GetNextIndex(position);
                position++;
            }

            sendDataToClient(clientId, tracks);
        }
Title: Re: MusicBee API
Post by: Steven on March 21, 2021, 03:41:06 AM
Are you still trying to change the play order of existing files for a shuffled playlist?
You wont be able to do it until i add API support for that.
NowPlayingList_QueueFilesNext() will add the files to the now playing list and queue them next - the equivalent of right clicking in the main panel/ Play Next.
Title: Re: MusicBee API
Post by: dandepeched on March 21, 2021, 10:03:25 AM
Are you still trying to change the play order of existing files for a shuffled playlist?
You wont be able to do it until i add API support for that.
NowPlayingList_QueueFilesNext() will add the files to the now playing list and queue them next - the equivalent of right clicking in the main panel/ Play Next.

I still do ;D  But this case is different because it works properly for MusicBee player, so behavior is inconsistent between player and API.
NowPlayingList_QueueFilesNext() adds file in the next position for Upcoming Tracks list - that's what I observe in MusicBee.

Also for the new API in v3.5, it would be cool to have all the NowPlayingList actions to be mirrored with the UpcomingTracksList actions.
Title: Re: MusicBee API
Post by: derTyp on August 28, 2021, 10:35:34 PM
Hi,

I just found out that some Metadata fields seem to be missing from the current API version (C#) e.g. the "Year(yyyy)" tag and virtual tags 25+. Would be nice if the API could be updated so all fields are available, I guess its just the "MetaDataType" enum that is missing some members.

Title: Re: MusicBee API
Post by: Steven on August 28, 2021, 11:51:14 PM
I will provide an updated API interface file at a later date but here is what you need
Code
        public enum MetaDataType
        {
            TrackTitle = 65,
            Album = 30,
AlbumUniqueId = 108,
            AlbumArtist = 31,        // displayed album artist
            AlbumArtistRaw = 34,     // stored album artist
            Artist = 32,             // displayed artist
            MultiArtist = 33,        // individual artists, separated by a null char
PrimaryArtist = 19,      // first artist from multi-artist tagged file, otherwise displayed artist
            Artists = 144,
            ArtistsWithArtistRole = 145,
            ArtistsWithPerformerRole = 146,
            ArtistsWithGuestRole = 147,
            ArtistsWithRemixerRole = 148,
            Artwork = 40,
            BeatsPerMin = 41,
            Composer = 43,           // displayed composer
            MultiComposer = 89,      // individual composers, separated by a null char
            Comment = 44,
            Conductor = 45,
            Custom1 = 46,
            Custom2 = 47,
            Custom3 = 48,
            Custom4 = 49,
            Custom5 = 50,
            Custom6 = 96,
            Custom7 = 97,
            Custom8 = 98,
            Custom9 = 99,
            Custom10 = 128,
            Custom11 = 129,
            Custom12 = 130,
            Custom13 = 131,
            Custom14 = 132,
            Custom15 = 133,
            Custom16 = 134,
Decade = 105,
            DiscNo = 52,
            DiscCount = 54,
            Encoder = 55,
            Genre = 59,
            Genres = 143,
            GenreCategory = 60,
            Grouping = 61,
            Keywords = 84,
            HasLyrics = 63,
            Lyricist = 62,
            Lyrics = 114,
            Mood = 64,
            Occasion = 66,
            Origin = 67,
            Publisher = 73,
            Quality = 74,
            Rating = 75,
            RatingLove = 76,
            RatingAlbum = 104,
            Tempo = 85,
            TrackNo = 86,
            TrackCount = 87,
            Virtual1 = 109,
            Virtual2 = 110,
            Virtual3 = 111,
            Virtual4 = 112,
            Virtual5 = 113,
            Virtual6 = 122,
            Virtual7 = 123,
            Virtual8 = 124,
            Virtual9 = 125,
            Virtual10 = 135,
            Virtual11 = 136,
            Virtual12 = 137,
            Virtual13 = 138,
            Virtual14 = 139,
            Virtual15 = 140,
            Virtual16 = 141,
            Virtual17 = 149,
            Virtual18 = 150,
            Virtual19 = 151,
            Virtual20 = 152,
            Virtual21 = 153,
            Virtual22 = 154,
            Virtual23 = 155,
            Virtual24 = 156,
            Virtual25 = 157,
Virtual26 = 185,
Virtual27 = 186,
Virtual28 = 187,
Virtual29 = 188,
Virtual30 = 189,
Virtual31 = 190,
Virtual32 = 191,
            Year = 88,
YearOnly = 35,
            SortTitle = 163,
            SortAlbum = 164,
            SortAlbumArtist = 165,
            SortArtist = 166,
            SortComposer = 167,
            Work = 168,
            MovementName = 169,
            MovementNo = 170,
            MovementCount = 171,
            ShowMovement = 172,
            Language = 173,
            OriginalArtist = 174,
            OriginalYear = 175,
            OriginalTitle = 177,
            InstrumentsPerformers = 182
        }

Title: Re: MusicBee API
Post by: derTyp on August 29, 2021, 01:31:08 PM
Thanks, much appreciated
Title: Re: MusicBee API
Post by: jkfranks9 on September 20, 2021, 04:49:49 PM
Steven, I've been able to successfully retrieve music tracks and playlists, but I don't see any way to get music video files using the API. Is this something that exists but is not obvious? If it doesn't exist, any plans to add video retrieval?

Many thanks for providing this API!
Title: Re: MusicBee API
Post by: boroda on December 11, 2022, 10:33:44 AM
Steven, could you implement API function MbApiInterface.MB_UnRegisterCommand("Hotkey description ")? Or even better, MbApiInterface.MB_UnRegisterCommands("Hotkey descriptions"), where "Hotkey descriptions" can contain "*" wildchar? something like "Tagging Tools: *". there is no need to support "?" wildchar, and even support for "*" is required only at the end of hotkeys description string (at least personally for me).
Title: Re: MusicBee API
Post by: Piotr on February 20, 2023, 09:59:13 PM
Is the PlayerRepeatChanged notification sent correctly by MB?
I can read the RepeadMode enum with the mbApiInterface.Player_GetRepeat() function, but unfortunately I don't receive this notification, hence my question.
Title: Re: MusicBee API
Post by: Steven on February 21, 2023, 08:05:10 AM
it looks the plugin initialisation needs to include the tag notifications for it to be received
            about.ReceiveNotifications = (ReceiveNotificationFlags.PlayerEvents | ReceiveNotificationFlags.TagEvents);
Title: Re: MusicBee API
Post by: Piotr on February 21, 2023, 01:10:32 PM
Thanks, your advice was spot-on.
Title: Re: MusicBee API
Post by: boroda on December 06, 2023, 08:44:20 PM
using MB 3.6.8736 P:

go to prefs> tags (2)> configure fields. tag "time" has type "String" (hard-coded). but Setting_GetDataType() returns type "DataType.DateTime".

i think all tag types displayed in prefs and returned by API must be consistent. as for tag "time" i would prefer if it had type "DateTime" both in prefs and returned by API.
Title: Re: MusicBee API
Post by: BoringName on January 16, 2024, 09:32:04 AM
Hi,

Just checking if it's possible to get all songs with the same AlbumUniqueId without iterating over the whole library.

I tried
Library_QueryFilesEx("AlbumUniqueId=xxxxxxxxxx", out songList)

Also with a query
Code
string query = "<SmartPlaylist>\n";
            query += "<Source Type=\"1\">\n";
            query += "<Conditions CombineMethod=\"All\">\n";
            query += "<Condition Field=\"AlbumUniqueId\" Comparison=\"Is\" Value=\"" + albumUniqueId + "\" />\n";
            query += "</Conditions>\n";
            query += "</Source>\n";
            query += "</SmartPlaylist>\n";

AlbumUniqueId is not listed in the dropdown when creating a smart playlist and I tried setting it to any field to match a particular AlbumUniqueId but it didn't find any matches.

I've gotten by just getting matches for album name and album artist but I think AlbumUniqueId would be more accurate.

Thanks.
Title: Re: MusicBee API
Post by: Steven on January 16, 2024, 07:52:50 PM
I've gotten by just getting matches for album name and album artist but I think AlbumUniqueId would be more accurate.
thats right. I will have a look tonight
Title: Re: MusicBee API
Post by: Steven on January 19, 2024, 08:49:20 AM
I tried
Library_QueryFilesEx("AlbumUniqueId=xxxxxxxxxx", out songList)
this definitely works, i expect the 2nd approach would as well. The matching files need to be in the music library, audiobooks or inbox

Title: Re: MusicBee API
Post by: BoringName on January 19, 2024, 09:28:02 AM
I don't know how many times I tried this the other day and just couldn't get it to work with either approach.....it was a lot.

Just tried again after reading your reply and it worked first go with the first method. No idea what I was doing wrong. Thanks.
Title: Re: MusicBee API
Post by: BoringName on January 22, 2024, 01:42:15 AM
First off. Is there an API command that replicates the Right Click->Play More->Play Album Now option? If there is you can probably ignore the rest of the post.

Edit: Before you waste time reading this stupidly long post. I fixed the problem. Solution posted below.

I couldn't find one so I used the following code to try and replicate it.
Code
Plugin.MbApiInterface.Library_QueryFilesEx("AlbumUniqueId=" + uniqueAlbumId, out songsList);
if (songsList.Length > 0)
{
    Plugin.MbApiInterface.NowPlayingList_PlayNow(songsList[0]);
    if (songsList.Length > 1)
        {
            songsList = songsList.Skip(1).ToArray();//remove first song from array
            Plugin.MbApiInterface.NowPlayingList_QueueFilesNext(songsList);
        }
}

Ok strap in, this is going to be a bastard to explain.

When the now playing list is empty. This works as intended. But if the list is populated and already playing something, instead of playing the first song from the album I am trying to play now, it just starts playing whatever the next song in the now playing list was and queues up all the songs from the album I select next. But it puts the first song at the end of the current album in the list.

This might be a better way to explain it. Each letter is songs from an album in the now playing list. E is one album, D is another etc...
Lets say the list looks like the following and the * is the current song playing.
D*
D
D
D
F
F
F

Now if I want to play album now for Album G.
Instead of looking like this -
D
G*
G
G
G
D
D
D
F
F
F
It looks like this -
D
D*
G
G
G
D
D
G <-- this song should be playing now. But instead it's inserted after Album D.
F
F
F

This only occurs if I try play now(using my code above) on 2 albums in a row without letting the song change. If I play now on an album, let the song fully play through so it goes to a second song, then play now on a second album, it will work correctly. Or I can manually double click a different song then play now on a second album and it works. It's only if I play now on an album and then try a second album while that first song is still playing. And it doesn't appear to matter how far through that song has played.

Also
Plugin.MbApiInterface.Library_QueryFilesEx("AlbumUniqueId=" + uniqueAlbumId, out songsList);

The output string array is not in track number order. Is there a way to do that or do I have to query all the songs in the array to sort it myself?

Using the Right Click->Play More->Play Album Now option works as you would expect and queues the songs in track number order.

It's a strange one.

edit: Ok I might be wrong about the track number order. It does appear to be in order for most but I do have one album that seems to be out of order. But it only has 3 tracks labelled as 2 of 11, 5 of 11 and 11 of 11. The last 2 are out of order,  I'll do some more testing on that one.

edit2: So most albums are coming through in track order but lucky me the first one I just happened to test initially did not. I've tried a bunch of things but they don't come through in track order.
The album Arrival by ABBA. I only have 3 songs in this library from that album
Dancing Queen track 2 of 11
Knowing Me Knowing You track 5 of 11
Fernando track 11 of 11

All other info for each track is the same. Sorting tab is the same. But for whatever reason, Fernando always comes through second in the array instead of third.

Tried changing the track numbers to 1, 2, 3. deleting the 11 field. I even renamed the file names to put the track numbers at the start of the song name like the rest of the library has and Fernando still comes through second.

I can go through and sort them myself but figured you might be interested if it's not working as intended.
Title: Re: MusicBee API
Post by: BoringName on January 22, 2024, 03:15:46 AM
If I remove the line to that queues the remainder of the album next,  it adds the first song correctly and starts playing it. So I think the issue is sending a Play Now command immediately followed by a Queue Next command. I've also found another album that doesn't come through in track number order. Maybe coincidentally it is only 3 tracks as well....

And I should probably make separate threads for these issues instead of dumping everything in here. Sorry.

edit: It also has the same problem if I replace
Code
Plugin.MbApiInterface.NowPlayingList_QueueFilesNext(songsList);

with
Code
foreach(string s in songsList)
                        {
                            Plugin.MbApiInterface.NowPlayingList_QueueNext(s);
                        }
Title: Re: MusicBee API
Post by: BoringName on January 22, 2024, 10:45:35 PM
I fixed it by swapping around the code.

Code
Plugin.MbApiInterface.Library_QueryFilesEx("AlbumUniqueId=" + uniqueAlbumId, out songsList);
if (songsList.Length > 0)
{
    Plugin.MbApiInterface.NowPlayingList_QueueFilesNext(songsList);
    Plugin.MbApiInterface.NowPlayingList_PlayNow(songsList[0]);
}

I thought Plugin.MbApiInterface.NowPlayingList_PlayNow would add the song to the now playing list and start playing it.

But I think it's meant to play a song that's already in the now playing list and if that song doesn't exist in the list, it just plays the next song in the now playing list and adds the song you specified to the end of what has recently added.