我正在制作音乐播放器应用程序。我正在使用ListBox来显示歌曲。当用户添加歌曲时,它会显示歌曲的完整路径。但我希望它只显示歌曲名称(歌曲可以位于任何驱动器的任何文件夹中)。 Windows媒体播放器控件正在播放歌曲。提前谢谢!
答案 0 :(得分:0)
所以你想只从歌曲的整个路径中提取歌曲名称。一个简单的棘手的逻辑将做这些。这是VBA
sub song_name_extractor()
song_path = "c:\songs\favret\mylove.mp3" ' Assume this is where the song is
song_name = Right(song_path, Len(song_path) - InStrRev(song_path, "\"))
Msgbox song_name 'outputs mylove.mp3
song_name = Left(song_name, InStrRev(song_name, ".") - 1)
Msgbox song_name ' outputs only mylove removes extensions of file
end sub
阐释:
Right Func, cuts the right part of the string into sub-string of given number
Len Func, To find the length of the string
InStrRev Fun, gives the point of occurrence, of the given character in a string
searching from right to left
Left Func, cuts the Left part of the string into sub-string of given number
答案 1 :(得分:0)
我会这样做:
1.创建一个可以保存歌曲信息的对象
2.创建一个列表,其中包含播放列表中的所有歌曲
3.将该列表作为数据源添加到列表框中。通过设置.DisplayMember,您将告知属性将在列表框中以listitemtext显示。
4.当listindex更改时,获取存储在listbox.SelectedItem中的对象,并将其键入歌曲对象以使用它。
Public Class Form1
Structure SongObject
Public SongPath As String
Public NameNoExtension As String
Public SongLength As Integer
Public SongRating As Integer
Private _FileName
Public Property FileName() As String
Get
Return _filename
End Get
Set(ByVal value As String)
_FileName = value
End Set
End Property
Public Sub New(ByVal path As String)
SongPath = path
FileName = IO.Path.GetFileName(path)
NameNoExtension = IO.Path.GetFileNameWithoutExtension(path)
SongLength = 0 'fix
SongRating = 5 'fix
End Sub
End Structure
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim musicpath As String = "C:\Users\Public\Music\Sample Music\"
'Load songs into listbox
ListBox1.DisplayMember = "FileName"
Dim songs As New List(Of SongObject)
For Each f As String In IO.Directory.GetFiles(musicpath, "*.mp3")
songs.Add(New SongObject(f))
Next
ListBox1.DataSource = songs
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
'Get songitem
Dim SelectedSong As SongObject = CType(ListBox1.SelectedItem, SongObject)
MsgBox("Path:" & SelectedSong.SongPath & vbCrLf & "FileName:" & SelectedSong.FileName)
'Todo: play selected song...
End Sub
End Class
使用IO.Path.GetFileName(path)和IO.Path.GetFileNameWithoutExtension(path)获取文件名而不是右/左/ instr / mid等。