使用PHP Last.fm API

If you’re like me and listen to music while coding, and you like keeping a record of the songs you’ve listened to, then you’ve probably heard of Last.fm.

如果您像我一样,边编码边听音乐,并且喜欢记录自己听过的歌曲,那么您可能听说过Last.fm。

Last.fm is a social website which has a music recommendation engine at its core. It keeps track of its users’ music tastes, and offers events, wikis, and discographies for artists. All of the data is gathered using a Audioscrobbler database plugin installed with each user’ music player (Spotify, Winamp, iTunes, etc.). Above all, Last.fm has an rich and impressive API which developers can use to build mobile and web mashups.

Last.fm是一个社交网站,其核心是音乐推荐引擎。 它跟踪用户的音乐喜好,并为艺术家提供事件,Wiki和唱片。 使用每个用户的音乐播放器(Spotify,Winamp,iTunes等)安装的Audioscrobbler数据库插件收集所有数据。 最重要的是,Last.fm具有丰富而令人印象深刻的API,开发人员可以使用它们来构建移动和Web混搭。

If you are building a site for a band or artist and you want to make it more social using Last.fm, it’s a must to use their API. In this way artists and fans can become connected and fans can stay up to date on concerts and new albums.

如果您要为乐队或歌手建立网站,并希望使用Last.fm使网站更具社交性,则必须使用其API。 通过这种方式,艺术家和歌迷可以建立联系,歌迷可以在音乐会和新专辑上保持最新状态。

In this article I show you how to query the Last FM API to get information to build a fan website for Coldplay. We start with getting the basics about the band, then get their most popular song, the contents of their albums, and a list of the events where the band is going to play for fans to get tickets.

在本文中,我将向您展示如何查询Last FM API来获取信息,以建立Coldplay的粉丝网站。 我们首先了解乐队的基础知识,然后获得他们最受欢迎的歌曲,专辑的内容以及乐队将要参加的活动清单,以吸引歌迷获得门票。

入门 (Getting Started)

In order to get an API account, you need to have a Last.fm user account first. Login with your user account and then go to www.last.fm/api/account to get an API account. When you apply for an API account you have 4 options: Commercial Use, Commercial-Promotional Use, Bespoke Use, and Non-commercial Use. Specify your application’s name, a description, and website, and you’ll be given an API key and secret.

为了获得一个API帐户,您需要首先拥有一个Last.fm用户帐户。 使用您的用户帐户登录,然后访问www.last.fm/api/account以获取API帐户。 当您申请API帐户时,您有4种选择:商业用途,商业促销用途,定制用途和非商业用途。 指定应用程序的名称,描述和网站,然后您会获得API密钥和密码。

As with all major API services, there are a bunch of different libraries available for different programming languages, including PHP. I’ll be using the PHP Last.fm API library created by Felix Bruns and hosted on GitHub. Clone the project or download the ZIP file and extract it into your working directory.

与所有主要的API服务一样,有很多不同的库可用于不同的编程语言,包括PHP。 我将使用由Felix Bruns创建并托管在GitHub上的PHP Last.fm API库 。 克隆项目或下载ZIP文件并将其解压缩到您的工作目录中。

发出请求 (Issuing Requests)

The Last.fm API is REST-based and uses XML-formatted responses, but this detail is abstracted from us by the PHP Last.fm API library. We can interface with Last.fm through the methods.

Last.fm API是基于REST的,并使用XML格式的响应,但是此细节是通过PHP Last.fm API库从我们那里抽象出来的。 我们可以通过这些方法与Last.fm进行交互。

The Last.fm artist resource returns information about an artist, events the artist is performing, and the artist’s most popular tracks. To start, let’s search for an artist using the library’s Artist::search() method.

Last.fm艺术家资源返回有关艺术家的信息,该艺术家正在表演的事件以及该艺术家最受欢迎的曲目。 首先,让我们使用库的Artist::search()方法Artist::search()

<?php
require __DIR__ . "/src/lastfm.api.php";
require __DIR__ . "/config.php";

// set api key
CallerFactory::getDefaultCaller()->setApiKey(LAST_FM_API_KEY);

// search for the Coldplay band
$artistName = "Coldplay";
$limit = 1;
$results = Artist::search($artistName, $limit);

echo "<ul>";
while ($artist = $results->current()) {
    echo "<li><div>";
    echo "Artist URL: " . $artist->getUrl() . "<br>";
    echo '<img src="' . $artist->getImage(4) . '">';
    echo "</div></li>";

    $artist = $results->next();
}
echo "</ul>";

Artist::getEvents() returns a listing of events the artist is playing.

Artist::getEvents()返回艺术家正在播放的事件列表。

<?php
// search for the Coldplay band events
$artistName= "ColdPlay";
$events = Artist::getEvents($artistName);
if (!empty($events)) {
    echo "<ul>";
    foreach ($events as $key => $evt) {
        echo "<li><div>";
        echo "Event Number: " . ($key + 1) . "<br>";
        echo "Event Name: " . $evt->getTitle() . "<br>";
        echo "Artists: " . implode(", ", $evt->getArtists()) . "<br>";
        echo "Venue: " . $evt->getVenue()->getName() . "<br>";
        echo "Location: " . 
            $evt->getVenue()->getLocation()->getStreet() . " " .
            $evt->getVenue()->getLocation()->getCity() . " " .
            $evt->getVenue()->getLocation()->getCountry() . "<br>";
        echo "Description: " . $evt->getDescription() . "<br>";
        echo "Event URL: " . $evt->getUrl() . "<br>";
        echo "</div></li>";
    }
    echo "</ul>";
}

Artist::getTopTracks() gets the post popular tracks by an artist.

Artist::getTopTracks()获取艺术家发布的热门曲目。

<?php
// get top tracks for Coldplay
$artistName= "Coldplay";
$tracks = Artist::getTopTracks($artist_name);
echo "<ul>";
foreach($tracks as $key => $track) {
    echo "<li><div>";
    echo "Track Number: " . ($key + 1) . "<br>";
    echo "Title: " . $track->getName() . "<br>";
    echo "Played: " . $track->getPlayCount() . " time(s)<br>";
    echo "Duration: " . $track->getDuration() . " seconds<br>";
    echo "Track URL: " . $track->getUrl() . "<br>";
    echo "</div></li>";
}
echo "</ul>";

The album resource returns information about artists’ albums. Album::getInfo() retrieves the full track-listing for an album.

专辑资源返回有关艺术家专辑的信息。 Album::getInfo()检索Album::getInfo()的完整曲目列表。

<?php
// get top tracks for Coldplay
$artistName= "Coldplay";
$albumName = "Mylo Xyloto";
$album = Album::getInfo($artistName, $albumName);
echo "<div>";
echo "Number of Plays: " . $album->getPlayCount() . " time(s)<br>";
echo 'Cover: <img src="' . $album->getImage(4) . '"><br>";
echo "Album URL: " . $album->getUrl() . "<br>";
echo "</div>";

验证您的混搭 (Authenticating Your Mashup)

Music is a big part of social interaction; I like to see what my friends are listening to so I can potentially discover artists I’ve never heard before and become a fan. We can get user information from the API and use it in our own mashup.

音乐是社交互动的重要组成部分。 我喜欢看朋友们在听什么,因此我有可能发现以前从未听过的艺术家并成为粉丝。 我们可以从API获取用户信息,并在我们自己的混搭中使用它。

It’s a bit odd that Last.fm doesn’t use OAuth as other major social sites do. Instead they use a similar approach but having a single token instead of a access token, and access token secret as the Oauth uses. A description of the flow can be found at www.last.fm/api/webauth. But again, this is mostly an implementation detail that’s been abstracted away by our library.

Last.fm不像其他主要社交网站那样使用OAuth,这有点奇怪。 取而代之的是,他们使用类似的方法,但使用单个令牌而不是访问令牌,并且使用Oauth使用的访问令牌密钥。 可以在www.last.fm/api/webauth上找到该流程的描述。 再次强调,这主要是实现细节,该细节已由我们的库提取。

The first step is to request permission to retrieve information about a user. Once the mashup is authenticated, Last.fm returns to a callback URL after which we can retrieve the desired information.

第一步是请求权限以检索有关用户的信息。 混搭通过身份验证后,Last.fm返回到回调URL,之后我们可以检索所需的信息。

<?php
require __DIR__ . "/src/lastfm.api.php";
require __DIR__ . "/config.php";

CallerFactory::getDefaultCaller()->setApiKey(LAST_FM_API_KEY);

// create the callback url
$callback = "http://" . $_SERVER["HTTP_HOST"] . "/callback.php";
$url = "http://www.last.fm/api/auth/?api_key=" . LAST_FM_API_KEY . "&cb=" . $callback;
echo '<a href="' . $url . '">Authenticate with Last.fm</a>';

A user will click on the link and be taken to the Last.fm authentication page. After the user is authenticated, she will be redirected back to site and we’ll have the token necessary to issue requests.

用户将单击链接,然后转到Last.fm身份验证页面。 用户通过身份验证后,她将被重定向回站点,我们将拥有发出请求所必需的令牌。

<?php
// get last top 10 track listen by user "gafitescu"
$user = "gafitescu";
$tracks = User::getRecentTracks($user, 10);
echo "<ul>";
foreach($tracks as $key => $track) {
    echo "<li><div>";
    echo "Track Number: " . ($key + 1) . "<br>";
    echo "Title: " . $track->getName() . "<br>";
    echo "Artist: " . $track->getArtist() . "<br>";
    echo "Album: " . $track->getAlbum() . "<br>";
    echo "Track URL: " . $track->getUrl() . "<br>";
    echo "</div></li>";
}
echo "</ul>";

// get user's friends
$friends = User::getFriends($user);
echo "<ul>";
foreach ($friends as $friend) {
    echo "<li><div>";
    echo "Friend: " . $friend->getName() . "<br>";
    echo "Country: " . $friend->getCountry() . "<br>";
    echo "Age: " . $friend->getAge() . "<br>";
    echo "</div></li>";
}
echo "</ul>";

结论 (Conclusion)

In a world that everything tends to be more and more connected, and now that Open Graph is becoming standard, connecting fans with their favorite artists its very important, and Last FM does it very well through its API. Being open allow you to enhance your community and raise awareness of your product/idea and the best way to do that it’s by having a public API.

在当今世界之间,事物之间的联系越来越紧密的情况下,Open Graph逐渐成为标准,将粉丝与喜爱的艺术家联系起来非常重要,而Last FM通过其API则表现出色。 开放让您可以增强社区并提高对产品/想法的认识,而最好的方法就是拥有公共API。

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/using-the-last-fm-api/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值