비버놀로지

[Spotify 스포티파이] 11. Spring Boot 추천서비스 본문

OPEN API 활용

[Spotify 스포티파이] 11. Spring Boot 추천서비스

KUNDUZ 2021. 3. 25. 22:13
728x90
import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.specification.Recommendations;
import com.wrapper.spotify.requests.data.browse.GetRecommendationsRequest;
import org.apache.hc.core5.http.ParseException;

import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

public class GetRecommendationsExample {
  private static final String accessToken = "taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk";

  private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
    .setAccessToken(accessToken)
    .build();
  private static final GetRecommendationsRequest getRecommendationsRequest = spotifyApi.getRecommendations()
//          .limit(10)
//          .market(CountryCode.SE)
//          .max_popularity(50)
//          .min_popularity(10)
//          .seed_artists("0LcJLqbBmaGUft1e9Mm8HV")
//          .seed_genres("electro")
//          .seed_tracks("01iyCAUm8EvOFqVWYJ3dVX")
//          .target_popularity(20)
    .build();

  public static void getRecommendations_Sync() {
    try {
      final Recommendations recommendations = getRecommendationsRequest.execute();

      System.out.println("Length: " + recommendations.getTracks().length);
    } catch (IOException | SpotifyWebApiException | ParseException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }

  public static void getRecommendations_Async() {
    try {
      final CompletableFuture<Recommendations> recommendationsFuture = getRecommendationsRequest.executeAsync();

      // Thread free to do other tasks...

      // Example Only. Never block in production code.
      final Recommendations recommendations = recommendationsFuture.join();

      System.out.println("Length: " + recommendations.getTracks().length);
    } catch (CompletionException e) {
      System.out.println("Error: " + e.getCause().getMessage());
    } catch (CancellationException e) {
      System.out.println("Async operation cancelled.");
    }
  }

  public static void main(String[] args) {
    getRecommendations_Sync();
    getRecommendations_Async();
  }
}

 

위의 코드를 활용을 해서 음악을 추천 받을 수 있다.

 

그리고 seed를 활용을 해서 특정한 조건에 해당하는 음악을 추천 받을 수 있다.

 

seed_genres("electro"), seed_genres("happy") 등 다양한 장르를 넣어서 추천 받을 수 있다.

 

import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.specification.Recommendations;
import com.wrapper.spotify.requests.data.browse.GetRecommendationsRequest;
import org.apache.hc.core5.http.ParseException;

import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

public class GetRecommendationsExample {
  private static final String accessToken = "taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk";

  private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
    .setAccessToken(accessToken)
    .build();

  public static void getRecommendations_Sync() {
  GetRecommendationsRequest getRecommendationsRequest = spotifyApi.getRecommendations()
          .limit(10)
          .market(CountryCode.KR)
//          .max_popularity(50)
          .min_popularity(10)
//          .seed_artists("0LcJLqbBmaGUft1e9Mm8HV")
          .seed_genres("happy")
//          .seed_tracks("01iyCAUm8EvOFqVWYJ3dVX")
//          .target_popularity(20)
    .build();
    try {
      final Recommendations recommendations = getRecommendationsRequest.execute();

      System.out.println("Length: " + recommendations.getTracks().length);
    } catch (IOException | SpotifyWebApiException | ParseException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }


  public static void main(String[] args) {
    getRecommendations_Sync();
  }
}

위의 코드를 사용하면 인기도가 10 이상인 음악이어야 하고, 장르가 happy인 음악을 추천 받을 수 있다.

 

그리고 limit은 10이므로 10개의 노래를 추천받을 수 있다.

 

Track track=null;	//spotify에서 제공하는 track
Artist artist=null;	//spotify에서 제공하는 artist

위의 두개는 따로 클래스 생성없이 spotify maven을 통해 사용 할 수 있다.

 

			for (int i = 0; i < recommendations.getTracks().length; i++) {

				track=getTrack_Sync(recommendations.getTracks()[i].getId());
				artist=getArtist_Sync(recommendations.getTracks()[i].getArtists()[0].getId());
				//제목, 장르, 가수, 앨범, 미리듣기, 이미지, 인기도, 음악ID, 가수ID, 앨범ID, 추천횟수
				//제목
                System.out.println(recommendations.getTracks()[i].getName());
				//장르
				String genres="";

				for (String s : artist.getGenres()) {
					genres=genres.concat(s).concat(",");
				}
				System.out.println(genres);
				//가수
				System.out.println(track.getArtists()[0].getName());
				//앨범
				System.out.println(track.getAlbum().getName());
				//미리듣기
				System.out.println(recommendations.getTracks()[i].getPreviewUrl());
				//이미지
				System.out.println(track.getAlbum().getImages()[0].getUrl());
				//음악ID
				System.out.println(recommendations.getTracks()[i].getId());
				//가수ID
				System.out.println(recommendations.getTracks()[i].getArtists()[0].getId());
				//앨범ID
				System.out.println(track.getAlbum().getId());
				//인기도
				System.out.println(String.valueOf(track.getPopularity()));
				//발매일
				System.out.println(track.getAlbum().getReleaseDate());

						
				System.out.println("제목 : " + recommendations.getTracks()[i].getName() + " 가수 : "
					+ recommendations.getTracks()[i].getArtists()[0].getName() + " 미리듣기 : "
					+ recommendations.getTracks()[i].getPreviewUrl() + " 인기도: "
					+ track.getPopularity());

//				System.out.println("발매일 : "+track.getAlbum().getReleaseDate());
			}

 

위와 같은 코드를 활용을 해서 다양한 값을 정리해서 출력해 줄수 있다.

 

아래는 모든 코드를 합친 코드이다.

 

import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.specification.Recommendations;
import com.wrapper.spotify.requests.data.browse.GetRecommendationsRequest;
import org.apache.hc.core5.http.ParseException;

import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

public class GetRecommendationsExample {
  private static final String accessToken = "taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk";

  private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
    .setAccessToken(accessToken)
    .build();

  public static void getRecommendations_Sync() {
  GetRecommendationsRequest getRecommendationsRequest = spotifyApi.getRecommendations()
          .limit(10)
          .market(CountryCode.KR)
//          .max_popularity(50)
          .min_popularity(10)
//          .seed_artists("0LcJLqbBmaGUft1e9Mm8HV")
          .seed_genres("happy")
//          .seed_tracks("01iyCAUm8EvOFqVWYJ3dVX")
//          .target_popularity(20)
    .build();
    Track track=null;	//spotify에서 제공하는 track
	Artist artist=null;	//spotify에서 제공하는 artist
    try {
      final Recommendations recommendations = getRecommendationsRequest.execute();
    			for (int i = 0; i < recommendations.getTracks().length; i++) {

				track=getTrack_Sync(recommendations.getTracks()[i].getId());
				artist=getArtist_Sync(recommendations.getTracks()[i].getArtists()[0].getId());
				//제목, 장르, 가수, 앨범, 미리듣기, 이미지, 인기도, 음악ID, 가수ID, 앨범ID, 추천횟수
				//제목
                System.out.println(recommendations.getTracks()[i].getName());
				//장르
				String genres="";

				for (String s : artist.getGenres()) {
					genres=genres.concat(s).concat(",");
				}
				System.out.println(genres);
				//가수
				System.out.println(track.getArtists()[0].getName());
				//앨범
				System.out.println(track.getAlbum().getName());
				//미리듣기
				System.out.println(recommendations.getTracks()[i].getPreviewUrl());
				//이미지
				System.out.println(track.getAlbum().getImages()[0].getUrl());
				//음악ID
				System.out.println(recommendations.getTracks()[i].getId());
				//가수ID
				System.out.println(recommendations.getTracks()[i].getArtists()[0].getId());
				//앨범ID
				System.out.println(track.getAlbum().getId());
				//인기도
				System.out.println(String.valueOf(track.getPopularity()));
				//발매일
				System.out.println(track.getAlbum().getReleaseDate());

						
				System.out.println("제목 : " + recommendations.getTracks()[i].getName() + " 가수 : "
					+ recommendations.getTracks()[i].getArtists()[0].getName() + " 미리듣기 : "
					+ recommendations.getTracks()[i].getPreviewUrl() + " 인기도: "
					+ track.getPopularity());

//				System.out.println("발매일 : "+track.getAlbum().getReleaseDate());
			}
      System.out.println("Length: " + recommendations.getTracks().length);
    } catch (IOException | SpotifyWebApiException | ParseException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }


  public static void main(String[] args) {
    getRecommendations_Sync();
  }
}
728x90
Comments