Visual C++ 7.1Visual C++ 8.0COMVisual C++ 7.0Windows 2000Windows XPXML中级开发Visual StudioWindowsC++.NETC#
使用 C# 访问 iTunes 中的歌曲和播放列表






3.80/5 (8投票s)
2005年12月21日

142943

2483
如何使用 .NET 获取 iTunes 中的歌曲列表和歌曲信息。
引言
这是一个简单的示例,展示了如何与 iTunes 版本 6 进行交互。该示例展示了如何使用 C# 连接到 iTunes 版本 6,以及如何获取 iTunes 库或已保存播放列表中的歌曲列表。
该项目是在 VS 2005 中构建的。需要将 COM 对象 ITunes 1.6 的引用添加到您的项目中。您可以从 这里 获取 iTunes SDK。压缩包中包含的帮助文件非常有用。
在互联网上搜索,我找到了 这个 网站,它帮助我开始了这个小项目。
使用代码
我认为代码中的注释已经足够清楚。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using iTunesLib;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// initialize Itunes application connection
iTunesApp itunes = new iTunesLib.iTunesApp();
private void Form1_Load(object sender, EventArgs e)
{
// get main library playlist
IITLibraryPlaylist mainLibrary = itunes.LibraryPlaylist;
// get list of all playlists defined in
// Itunes and add them to the combobox
foreach (IITPlaylist pl in itunes.LibrarySource.Playlists)
{
comboBox1.Items.Add(pl.Name);
}
// get the tracks within the mainlibrary
GetTracks((IITPlaylist)mainLibrary);
// set the datagridview1 datasource to the datatable.
dataGridView1.DataSource = dataTable1;
}
// getthe tracks from the the specified playlist
private void GetTracks(IITPlaylist playlist)
{
long totalfilesize = 0;
dataTable1.Rows.Clear();
// get the collection of tracks from the playlist
IITTrackCollection tracks = playlist.Tracks;
int numTracks = tracks.Count;
for (int currTrackIndex = 1;
currTrackIndex <= numTracks; currTrackIndex++)
{
DataRow drnew = dataTable1.NewRow();
// get the track from the current tracklist
IITTrack currTrack = tracks[currTrackIndex];
drnew["artist"] = currTrack.Artist;
drnew["song name"] = currTrack.Name;
drnew["album"] = currTrack.Album;
drnew["genre"] = currTrack.Genre;
// if track is a fiile, then get the file
// location on the drive.
if (currTrack.Kind == ITTrackKind.ITTrackKindFile)
{
IITFileOrCDTrack file = (IITFileOrCDTrack)currTrack;
if (file.Location != null)
{
FileInfo fi = new FileInfo(file.Location);
if (fi.Exists)
{
drnew["FileLocation"] = file.Location;
totalfilesize += fi.Length;
}
else
drnew["FileLocation"] =
"not found " + file.Location;
}
}
dataTable1.Rows.Add(drnew);
}
lbl_numsongs.Text =
"number of songs: " + dataTable1.Rows.Count.ToString() +
", total file size: " +
(totalfilesize / 1024.00 / 1024.00).ToString("#,### mb");
}
private void comboBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
// get list of tracks from selected playlist
string playlist = comboBox1.SelectedItem.ToString();
foreach (IITPlaylist pl in itunes.LibrarySource.Playlists)
{
if (pl.Name == playlist)
{
GetTracks(pl);
break;
}
}
}
}
}
希望对您有所帮助,欢迎提出任何意见/反馈。