com.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayWithThreadApplication.java Source code

Java tutorial

Introduction

Here is the source code for com.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayWithThreadApplication.java

Source

/**
 * Copyright  2017 tesshu.com (webmaster@tesshu.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tesshu.subsonic.client.sample4_music_andmovie;

import com.tesshu.subsonic.client.SuccessObserver;
import com.tesshu.subsonic.client.controller.Search2Controller;
import com.tesshu.subsonic.client.controller.StreamController;
import com.tesshu.subsonic.client.model.Child;
import com.tesshu.subsonic.client.model.SearchResult2;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

import javax.annotation.Resource;

/**
 * Acquire Stream using format conversion of server and perform performance
 * while writing media to local. Writing ends after the performance starts.
 */
@SpringBootApplication
@ComponentScan(basePackages = { "com.tesshu.subsonic.client" })
public class StreamDownloadAndPlayWithThreadApplication extends Application {

    private static ApplicationContext context;

    private static final Log LOG = LogFactory.getLog(new Throwable().getStackTrace()[0].getClassName());

    private static String tmpPath = "target/tmp";

    @Resource
    private com.tesshu.subsonic.client.util.SubsonicConnectionConfig config;

    private File file = null;

    private String format = "mp3";

    public static void main(String[] args) {
        context = SpringApplication.run(StreamDownloadAndPlayWithThreadApplication.class, args);
        launch(args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Override
    public void start(Stage stage) throws Exception {

        Search2Controller search2 = context.getBean(Search2Controller.class);

        StreamController streamController = context.getBean(StreamController.class);

        SuccessObserver callback = context.getBean(SuccessObserver.class);

        SearchResult2 result2 = search2.get("e", null, null, null, null, 1, null, null);

        List<Child> songs = result2.getSongs();

        File tmpDirectory = new File(tmpPath);
        tmpDirectory.mkdir();

        int maxBitRate = 256;

        Child song = songs.get(0);

        new Thread(new Runnable() {
            public void run() {
                try {

                    streamController.stream(song, maxBitRate, format, null, null, null, null,

                            (subject, inputStream, contentLength) -> {

                                File dir = new File(
                                        tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                                dir.mkdirs();

                                file = new File(tmpPath + "/"
                                        + song.getPath().replaceAll("([^.]+?)?$", StringUtils.EMPTY) + format);

                                try {

                                    FileOutputStream fos = new FileOutputStream(file);
                                    BufferedInputStream reader = new BufferedInputStream(inputStream);

                                    byte buf[] = new byte[256];
                                    int len;
                                    while ((len = reader.read(buf)) != -1) {
                                        fos.write(buf, 0, len);
                                    }
                                    fos.flush();
                                    fos.close();
                                    reader.close();
                                    inputStream.close();

                                    LOG.info("download finished");

                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }, callback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        LOG.info("download thread start");

        new Thread(new Runnable() {
            public void run() {
                while (file == null || file.getPath() == null) {
                    LOG.info("wait file writing.");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    String path = Paths.get(file.getPath()).toUri().toString();
                    Group root = new Group();
                    Scene scene = new Scene(root, 640, 480);
                    Media media = new Media(path);
                    MediaPlayer player = new MediaPlayer(media);
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                while (MediaPlayer.Status.READY != player.getStatus()) {
                                    LOG.info(player.getStatus() + " : " + path);
                                    LOG.info(media.errorProperty());
                                    Thread.sleep(1000);
                                    if (MediaPlayer.Status.PLAYING == player.getStatus()) {
                                        LOG.info(player.getStatus() + " : " + path);
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    MediaView view = new MediaView(player);
                    ((Group) scene.getRoot()).getChildren().add(view);

                    Platform.runLater(() -> {
                        stage.setScene(scene);
                        stage.show();
                        player.play();
                    });

                }
            }
        }).start();

    }

}