I am messing around with the WMPLib component provided by Windows Media Player 12 (wmp.dll) in VB.NET with .NET Framework 3.5 SP1.
I am trying to retrieve a media item from my media library based on its name (assuming there are no duplicate names). At the moment, I'm grabbing the entire media library, and looping through every media item, and quitting the loop when I've found the correct media item. This works well (except for when a media item with that name cannot be found), but I was hoping there was a more efficient way of doing this.
Here is my code so far:
Public Class WMPTest
Private myWMP As WMPLib.IWMPCore
Private myMediaCollection As WMPLib.IWMPMediaCollection
Private myTrack As WMPLib.IWMPMedia
Private allTracks As WMPLib.IWMPPlaylist
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
myWMP = New WMPLib.WindowsMediaPlayer
myMediaCollection = myWMP.mediaCollection
allTracks = myMediaCollection.getAll
Dim theTrack As WMPLib.IWMPMedia = findTrack("Yellow Submarine")
MessageBox.Show(theTrack.name)
End Sub
Public Function findTrack(ByVal strTrackName As String) As WMPLib.IWMPMedia
For i As Integer = 0 To (allTracks.count - 1)
If allTracks.Item(i).name = strTrackName Then
myTrack = allTracks.Item(i)
Exit For
End If
Next
'myTrack is now the track that we wanted to retrieve
Return myTrack
End Function
End Class
So what I really want is a way to optimize findTrack开发者_运维技巧() to do its thing without looping through the entire media library (which could be huge). Anyone have a clue?
Just thinking about how I might try to conduct a faster search. I might create a couple Background Workers and then iterate through from 0 to allTracks.count - 1 in one of the workers and then in the other worker, iterate down from allTracks.count - 1 to 0. Then, whichever reaches it first, on the RunWorkerCompleted event, you can cancel async on the other worker. That could potentially cut the search time in half.
You could also run loops on a quarter of the list simultaneously by dividing (count -1) by 4 for 25%, and then you can subtract it from (count-1) for 75%, and then iterate up or down to the halfway point in another couple asynchronous workers. That could feasibly cut down your search time to 25% of the previous wait.
I see you're making a class to support your searching within the object and I don't know if Backgroundworkers actually function inside classes, so I could be way off.
Just an idea. I haven't done anything like this before, so I might be making it way harder than it needs to be. Good luck! Let me know what you find out.
Edit: If you go with background worker, I think you'll need to include this code within the for loop:
If BackgroundWorker1.CancellationPending Then
Exit For
End If
Simply use the "getByName" method of the IWMPMediaCollection interface ;)
精彩评论