public void download(final Context context) {

    String album = "*";
    String title = "*";
    String artist = "*";
    if (this instanceof Song) {
      Song song = (Song) this;
      title = song.getName();
      album = song.getAlbum().getName();
      artist = song.getArtist().getName();
    } else if (this instanceof Album) {
      Album a = (Album) this;
      if (a.getArtist().getName().trim().equals("") == false) {
        artist = a.getArtist().getName();
      }
      album = a.getName();
    } else if (this instanceof Artist) {
      Artist a = (Artist) this;
      artist = a.getName();
    }
    SyncTask task = new SyncTask(context, true);
    task.execute(
        "download",
        new BasicNameValuePair("name", title),
        new BasicNameValuePair("album", album),
        new BasicNameValuePair("artist", artist));
  }
Exemple #2
0
  /**
   * Determine if the item given is already in cart. An item is in the cart if there appears to have
   * an item with the same name or item is a song and the album which the song belongs to is already
   * in the card, or the album about to be added already have a song added in the cart.
   *
   * @param item The item to be added to the cart.
   * @param cart The user's cart.
   * @return True if the item is already in the cart. False otherwise.
   */
  public LinkedList<Stock> itemIsInCart(String item, LinkedList<Stock> cart) {
    if (cart.size() == 0) {
      System.out.println("Cart is empty");
      return null;
    }
    LinkedList<Stock> duplicated = new LinkedList<Stock>();

    for (Stock s : cart) {
      // If the same song is found in cart.
      if (item.equalsIgnoreCase(s.getTitle())) duplicated.add(s);

      // Find in cart to see if the songs in this album
      // is already added.
      else if (s.getType() == StockType.ALBUM) {
        Album album = (Album) s;
        for (Song song : album.getSongs()) {
          if (song.getTitle().equalsIgnoreCase(item)) duplicated.add(s);
        }
      } else if (s.getType() == StockType.SONG) {
        Song song = (Song) s;
        if (getSongAlbum(song).getTitle().equalsIgnoreCase(item)) {
          System.out.println(item);
          duplicated.add(s);
        }
      }
    }
    return duplicated;
  }
Exemple #3
0
  // zapisywanie playlisty
  public static void savePlaylist(File playlistFile, ObservableList<Song> songList) {
    BufferedWriter bw = null;

    try {
      File fileNew = playlistFile;

      // je¿eli nie istnieje to tworzymy plik
      if (!fileNew.exists()) {
        fileNew.createNewFile();
      }

      // bufor zapisu
      bw = new BufferedWriter(new FileWriter(fileNew, false));

      // pêtla zapisuj¹ca wszystkie œcie¿ki piosenek z playlisty
      for (Song song : songList) {
        bw.write(song.getPath());
        bw.newLine();
        bw.flush();
      }
    } catch (IOException ioe) {
      System.out.println("ERROR");
    } finally {
      // zamykanie pliku
      if (bw != null)
        try {
          bw.close();
        } catch (IOException ioe2) {
          System.out.println("ERROR");
        }
    }
  }
Exemple #4
0
 /**
  * Returns the total duration of the playlist.
  *
  * @return The duration of all the songs on the list in seconds.
  */
 public int getTotalTime() {
   int total = 0;
   for (Song s : songlist) {
     total = total + s.getDuration();
   }
   return total;
 }
  // wyœwietla wszystkie albumy
  private void drawAlbums() {
    for (int i = 0; i < albumList.size(); i++) {
      VBox vBox = new VBox(5);

      // ok³adka albumu
      Song tempSong = new Song(albumList.get(i).albumSongList.get(0));
      ImageView albumCover = new ImageView(tempSong.getAlbumCover());
      albumCover.setFitWidth(130);
      albumCover.setPreserveRatio(true);
      albumCover.setSmooth(true);
      albumCover.imageProperty().bind(tempSong.albumCoverProperty());

      // tytu³ albumu
      Text albumTitle = new Text(albumList.get(i).getAlbumTitle());
      albumTitle.getStyleClass().add("text");
      vBox.getChildren().addAll(albumCover, albumTitle);
      vBox.setAlignment(Pos.CENTER);

      // dodaje do ka¿dego albumu listener którym otwiera listê z piosenkami
      vBox.setOnMouseClicked(
          e -> {
            Text tempText = (Text) vBox.getChildren().get(1);
            for (int j = 0; j < albumList.size(); j++) {
              if (albumList.get(j).getAlbumTitle().equals(tempText.getText())) {
                showCurrentAlbum(albumList.get(j));
                break;
              }
            }
          });

      flowPane.getChildren().add(vBox);
    }
  }
Exemple #6
0
 /**
  * Given the title of the item, get the Stock object of the item.
  *
  * @param item The title of the item.
  * @return The Stock object of the item.
  */
 public Stock getItem(String item) {
   for (Album a : musicDb) {
     if (a.getTitle().equalsIgnoreCase(item)) return a;
     for (Song s : a.getSongs()) {
       if (s.getTitle().equalsIgnoreCase(item)) return s;
     }
   }
   return null;
 }
Exemple #7
0
 /**
  * Check if a given song belongs to the given album.
  *
  * @param song The name of the song.
  * @param album The title of the album.
  * @return True if the song belongs to the album. False otherwise.
  */
 public boolean songBelongsToAlbum(String song, String album) {
   for (Album a : musicDb) {
     if (a.getTitle().equalsIgnoreCase(album)) {
       for (Song s : a.getSongs()) {
         if (s.getTitle().equalsIgnoreCase(song)) return true;
       }
     }
   }
   return false;
 }
Exemple #8
0
 /**
  * Liefert eine Selektion der in diesem Objekt gespeicherten SongVarianten. Mit den uebergebenen
  * Selektoren kann bestimmt werden, welche Songs selektiert werden. Aenderungen in der
  * zurueckgegebenen Selektion wirken sich direkt auf das Original aus.
  *
  * <p>Vorbedinung: selectors ist ungleich null
  *
  * <p>Nachbedingung: der Rueckgabewert ist eine neu initialisierte Liste aus Songvarianten,
  * bestehend aus den selektierten Varianten von den selektierten Songs.
  */
 public List<SongVariante> getSongVarianten(List<Selector<Variante>> selectors) {
   List<SongVariante> songVarianten = new ArrayList<SongVariante>();
   for (Song song : this) {
     for (Variante variante : song.getVarianten()) {
       if (select(variante, selectors)) {
         songVarianten.add(new SongVariante(song, variante));
       }
     }
   }
   return songVarianten;
 }
Exemple #9
0
  /**
   * Searches for the given title in the song list and returns true or false
   *
   * @param title The song title to be searched for.
   * @return true or false depending on whether the song exists in the playlist.
   */
  public boolean searchSongByTitle(String title) {
    boolean exists = false;

    for (Song s : songlist) {
      if (s.getTitle().equals(title)) {
        exists = true;
      }
    }

    return exists;
  }
 /**
  * Returns the first matching song (or NULL) of given type + id combination
  *
  * @param resolver A ContentResolver to use.
  * @param type The MediaTye to query
  * @param id The id of given type to query
  */
 public static Song getSongByTypeId(ContentResolver resolver, int type, long id) {
   Song song = new Song(-1);
   QueryTask query = buildQuery(type, id, Song.FILLED_PROJECTION, null);
   Cursor cursor = query.runQuery(resolver);
   if (cursor != null) {
     if (cursor.getCount() > 0) {
       cursor.moveToPosition(0);
       song.populate(cursor);
     }
     cursor.close();
   }
   return song.isFilled() ? song : null;
 }
  public void playMusic() {
    play.reset();
    Song curSong = songs.get(position);

    Long curSongId = curSong.getMusicId();
    Uri trackUri =
        ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, curSongId);
    try {
      play.setDataSource(getApplicationContext(), trackUri);
    } catch (Exception e) {
    }
    play.prepareAsync();
  }
  protected void onRestartServiceData() throws IOException {
    Log.d(LOG_TAG, "MyService onRestartServiceData 1 " + position);
    songList = currentText.isEmpty() ? playlist : filteredPlaylist;
    final Song song = songList.get(position);
    if (previousSong != null) previousSong.setIsPlaying(false);
    previousSong = song;
    song.setIsPlaying(true);

    mediaPlayer.stop();
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setDataSource(song.path);
    mediaPlayer.prepare();
    mediaPlayer.start();
  }
Exemple #13
0
 /** Description: Sends a song rating to the remote server. */
 public void rate(Song song, boolean rating)
     throws RPCException, IOException, HttpResponseException, Exception {
   Map<String, Object> feedback_params = new HashMap<String, Object>(2);
   feedback_params.put("trackToken", song.getId());
   feedback_params.put("isPositive", rating);
   this.doCall("station.addFeedback", feedback_params, false, true, null);
 }
  /**
   * Updates the available songs list.
   *
   * <p>Updates the list accordingly to the entered filter phrase in the edit text box.
   */
  private void updateAvailableSongsListView() {
    filteredSongs = new ArrayList<Song>();
    String words[] = filterEditText.getText().toString().toLowerCase().split(" ");

    for (Song song : allSongs) {
      String name = song.getPath().toLowerCase();
      boolean matches = true;
      for (String word : words) {
        if (!name.contains(word)) matches = false;
      }
      if (matches) filteredSongs.add(song);
    }

    ((SongAdapter) availableSongsListView.getAdapter())
        .setItems(filteredSongs.toArray(new Song[] {}));
  }
Exemple #15
0
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
   // map to song layout
   LinearLayout songLay = (LinearLayout) songInf.inflate(R.layout.song, parent, false);
   // get title and artist views
   TextView songView = (TextView) songLay.findViewById(R.id.song_title);
   TextView artistView = (TextView) songLay.findViewById(R.id.song_artist);
   // get song using position
   Song currSong = songs.get(position);
   // get title and artist strings
   songView.setText(currSong.getTitle());
   artistView.setText(currSong.getArtist());
   // set position as tag
   songLay.setTag(position);
   return songLay;
 }
Exemple #16
0
 /**
  * Find the album in which the song belongs to.
  *
  * @param song The song.
  * @return Return the album which the song belongs to. Or return null if no album is found.
  */
 public Album getSongAlbum(Song song) {
   for (Album album : musicDb) {
     if (album.getAlbumID().equalsIgnoreCase(song.getAlbumID())) {
       return album;
     }
   }
   return null;
 }
 public void sortSongList(String sortBy) {
   try {
     Collections.sort((ArrayList<Song>) playlist, Song.getComparator(sortBy));
   } catch (Exception invalidSortKey) {
     invalidSortKey.printStackTrace();
     System.exit(-1);
   }
 }
Exemple #18
0
  /**
   * Search for the list of songs that matches the searchString.
   *
   * @param searchString The searchString that is typed into the text box in the page.
   * @return The list of songs grouped into Hash Table for easy access.
   */
  public HashMap<Album, LinkedList<Song>> searchForSong(String searchString) {
    HashMap<Album, LinkedList<Song>> results = new HashMap<Album, LinkedList<Song>>();

    // Traverse the database, inside each album, looks for the song
    // that contains the search string.
    for (Album a : musicDb) {
      LinkedList<Song> songs = new LinkedList<Song>();
      for (Song s : a.getSongs()) {
        if (s.getTitle().contains(searchString)) {
          songs.add(s);
        }
      }
      results.put(a, songs);
    }

    return results;
  }
  private void displaySearchResults(ArrayList<Song> results) {
    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
    alert.setTitle("Song Results! Click to add:");

    LinearLayout layout = new LinearLayout(getActivity());
    layout.setOrientation(LinearLayout.VERTICAL);

    for (final Song temp : results) {
      final TextView input = new TextView(getActivity());
      input.setText(temp.getArtist() + " " + temp.getTitle());
      layout.addView(input);

      input.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              addSong(temp.getTrackID());
            }
          });
    }

    alert.setPositiveButton(
        "Ok",
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            if (search != "") {
              searchSC(search);
              search = "";
              dialog.cancel();
            }
            // Do something with value!
          }
        });

    alert.setNegativeButton(
        "Cancel",
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
          }
        });

    alert.setView(layout);
    alert.show();
  }
 public Playlist searchFilter(String searchBy, String searchStr) {
   Playlist filteredList = new Playlist();
   if (Song.ARTIST_FIELD.equals(searchBy)) {
     for (Song song : playlist) {
       if (song.getArtist().toLowerCase().contains(searchStr.toLowerCase())) {
         System.out.println(song.toString());
         filteredList.playlist.add(song);
       }
     }
   } else if (Song.ALBUM_FIELD.equals(searchBy)) {
     for (Song song : playlist) {
       if (song.getAlbum().toLowerCase().contains(searchStr.toLowerCase())) {
         filteredList.playlist.add(song);
       }
     }
   } else if (Song.TITLE_FIELD.equals(searchBy)) {
     for (Song song : playlist) {
       if (song.getTitle().toLowerCase().contains(searchStr.toLowerCase())) {
         filteredList.playlist.add(song);
       }
     }
   } else {
     System.out.print("Invalid Search Field");
     System.exit(-1);
   }
   return filteredList;
 }
  public void playSong() {
    // play a song
    player.reset();
    Song playSong = songs.get(songPosition);
    songTitle = playSong.getTitle();
    long currSong = playSong.getId();

    // set Uri
    Uri trackUri =
        ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);

    try {
      player.setDataSource(getApplicationContext(), trackUri);
    } catch (Exception e) {
      Log.e("MUSIC SERVICE", "Error setting data source", e);
    }

    player.prepareAsync();
  }
  // pokazuje piosenki wybranego albumu
  private void showCurrentAlbum(Album album) {
    flowPane.getChildren().clear();

    Song tempSong = album.getSongs().get(0);
    // ok³adka albumu
    ImageView albumCover = new ImageView(tempSong.getAlbumCover());
    albumCover.imageProperty().bind(tempSong.albumCoverProperty());
    albumCover.setFitWidth(200);
    albumCover.setPreserveRatio(true);
    // tytu³ albumu
    Text albumTitle = new Text(tempSong.getAlbum());
    albumTitle.textProperty().bind(tempSong.albumProperty());
    albumTitle.setFont(new Font("Segoe UI Light", 20));
    albumTitle.setFill(Paint.valueOf("WHITE"));
    // VBox zawieraj¹cy ok³adkê i tytu³
    VBox albumData = new VBox(albumCover, albumTitle);
    flowPane.getChildren().addAll(albumData);

    loadSongs(album.getSongs());
  }
Exemple #23
0
 @Override
 public void executeMsg(final Environmental myHost, final CMMsg msg) {
   if ((whom != null)
       && (song == null)
       && (msg.amISource(whom))
       && (CMLib.flags().canBeSeenBy(whom, invoker()))) {
     if (trail == null) trail = new StringBuffer("");
     ensureCmds();
     if (cmds.containsKey("" + msg.sourceMinor())) trail.append(msg.sourceMinor() + ";");
   }
   super.executeMsg(myHost, msg);
 }
  public void playSong() {

    if (isPlaying) {
      stopSong();
    }
    if (getCurrentSong() != null) {
      playingThread = new Thread(this, "My Thread");
      playingSong = getCurrentSong();
      play(playingSong.getPath());
      playingThread.start();
      isPlaying = playingThread.isAlive(); // this seems to work but isAlive is not modified by stop
    }
  }
Exemple #25
0
  public void tagList(final Context context) {

    String album = "*";
    String title = "*";
    String artist = "*";
    if (this instanceof Song) {
      Song song = (Song) this;
      title = song.getName();
      album = song.getAlbum().getName();
      artist = song.getArtist().getName();
    } else if (this instanceof Album) {
      Album a = (Album) this;
      if (a.getArtist().getName().trim().equals("") == false) {
        artist = a.getArtist().getName();
      }
      album = a.getName();
    } else if (this instanceof Artist) {
      Artist a = (Artist) this;
      artist = a.getName();
    }
    showTagListDialog(context, title, album, artist);
  }
Exemple #26
0
  /**
   * Import a song into the MidiExporter to play or export.
   *
   * @param song The Song to convert to MIDI
   */
  public void importSong(Song song) {
    // Fetch important data from the song.
    // Meaning, metadata and the song itself.
    Beat[] beats = song.getBeatArray();
    this.song = song;

    // Create a track for each voice.
    int numVoices = song.getNumVoices();
    for (int voiceCount = 0; voiceCount < numVoices; voiceCount++) {
      sequence.createTrack();
    }

    // Iterate through each beat, adding each note to the corresponding
    // track.
    Track[] tracks = sequence.getTracks();
    for (int beat = 0; beat < beats.length; beat++) {
      Note[] firstHalf = beats[beat].getNotesFirstHalf();
      Note[] secondHalf = beats[beat].getNotesSecondHalf();
      // Iterate through each note in the beat, adding it to the
      // corresponding track.
      for (int note = 0; note < firstHalf.length; note++) {
        if (firstHalf[note] == secondHalf[note]) {
          createNote(firstHalf[note], 2 * beat, 2, tracks[note]);
        } else {
          createNote(firstHalf[note], 2 * beat, 1, tracks[note]);
          createNote(secondHalf[note], 2 * beat + 1, 1, tracks[note]);
        } // if/else
      } // for
    } // for

    try {
      setUpSequencer();
    } catch (MidiUnavailableException ex) {
      System.out.println("Unable to set up sequencer");
      // do nothing
    }
  }
Exemple #27
0
 private void initData() {
   artists = new HashMap();
   InputStream is =
       this.getClass().getClassLoader().getResourceAsStream("org/richfaces/demo/tree/data.txt");
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   byte[] rb = new byte[1024];
   int read;
   try {
     do {
       read = is.read(rb);
       if (read > 0) {
         os.write(rb, 0, read);
       }
     } while (read > 0);
     String buf = os.toString();
     StringTokenizer toc1 = new StringTokenizer(buf, "\n");
     while (toc1.hasMoreTokens()) {
       String str = toc1.nextToken();
       StringTokenizer toc2 = new StringTokenizer(str, "\t");
       String songTitle = toc2.nextToken();
       String artistName = toc2.nextToken();
       String albumTitle = toc2.nextToken();
       toc2.nextToken();
       toc2.nextToken();
       String albumYear = toc2.nextToken();
       Artist artist = getArtistByName(artistName, this);
       Album album = getAlbumByTitle(albumTitle, artist);
       album.setYear(new Integer(albumYear));
       Song song = new Song(getNextId());
       song.setTitle(songTitle);
       album.addSong(song);
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  public void showDownloadCompletionDialog(int code, Song s) {
    String song = s.getTitle();
    String artist = s.getArtist();
    switch (code) {
      case 0:
        JOptionPane.showMessageDialog(
            this.frame,
            "Download of "
                + song
                + " by "
                + artist
                + " is completed."
                + "\n"
                + "You can view the file in your Documents Folder."
                + "\n",
            "Successful Download",
            1);

        break;
      case 1:
        JOptionPane.showMessageDialog(
            this.frame,
            "Sorry, Download of "
                + song
                + " by "
                + artist
                + " has failed."
                + "\n"
                + "If the song is still playing, you can try downloading again."
                + "\n",
            "Download Failed",
            0);

        break;
    }
  }
Exemple #29
0
  /** Gets the default transmitter and receiver, and then links them. */
  private void linkTransmitterToReceiver() {
    try {
      // Set up the sequencer (including its tempo)
      sequencer.open();
      sequencer.setSequence(sequence);
      sequencer.setTempoInBPM(song.getBPM());

      // Get the system's default synthesizer and set that up, too.
      Synthesizer synth = MidiSystem.getSynthesizer();
      synth.open();

      // Get the receiver and transmitter to use and set those up.
      Receiver receiver = synth.getReceiver();
      Transmitter transmitter = sequencer.getTransmitter();
      transmitter.setReceiver(receiver);
    } catch (Exception ex) {
      // Something went wrong.
      ex.printStackTrace();
      System.exit(1);
    }
  }
Exemple #30
-1
  public void edit(final Context context) {

    String album = "*";
    String title = "*";
    String artist = "*";
    String editable = "";
    String typeName = "";
    if (this instanceof Song) {
      Song song = (Song) this;
      title = song.getName();
      album = song.getAlbum().getName();
      artist = song.getArtist().getName();
      editable = title;
      typeName = "track";
    } else if (this instanceof Album) {
      Album a = (Album) this;
      if (a.getArtist().getName().trim().equals("") == false) {
        artist = a.getArtist().getName();
      }
      album = a.getName();
      editable = album;
      typeName = "album";
    } else if (this instanceof Artist) {
      Artist a = (Artist) this;
      artist = a.getName();
      editable = artist;
      typeName = "artist";
    }
    showEditDialog(context, typeName, editable, title, album, artist);
  }