package org.robbins.raspberry.pi.service;

import org.robbins.raspberry.pi.exceptions.RaspberryPiAppException;
import org.robbins.raspberry.pi.model.PiAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import java.io.FileInputStream;
import java.io.InputStream;

@Service
public class PlaySoundAction implements PiActionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PlaySoundAction.class);

    @Value("${base.sound.files.directory}")
    private String BASE_SOUND_DIRECTORY;

    @Override
    public void invokeAction(PiAction action) throws RaspberryPiAppException {
        LOGGER.debug("Invoking action: {}", action);

        try {
            InputStream in = new FileInputStream(BASE_SOUND_DIRECTORY + action.getValue());

            // create an audiostream from the inputstream
            AudioStream audioStream = new AudioStream(in);

            // play the audio clip with the audioplayer class
            AudioPlayer.player.start(audioStream);
        } catch (Exception e) {
            throw new RaspberryPiAppException(e.getMessage(), e);
        }
    }
}

@@ -319,69 +319,94 @@
 ce;%0A
+%0A
 import 
-sun.audio.AudioPlayer;%0Aimport sun.audio
+javax.sound.sampled.AudioInputStream;%0Aimport javax.sound.sampled
 .AudioS
-trea
+yste
 m;%0A
-%0A
 impo
@@ -416,27 +416,69 @@
 java
-.io.FileInputStream
+x.sound.sampled.Clip;%0Aimport javax.sound.sampled.FloatControl
 ;%0Aim
@@ -490,27 +490,20 @@
 java.io.
-InputStream
+File
 ;%0A%0A@Serv
@@ -914,16 +914,21 @@
         
+Audio
 InputStr
@@ -935,32 +935,88 @@
 eam 
-in = new FileInputStream
+audioInputStream = AudioSystem.getAudioInputStream(%0A                    new File
 (BAS
@@ -1053,18 +1053,18 @@
 Value())
+)
 ;
-%0A
 %0A       
@@ -1072,226 +1072,292 @@
     
-// create an audiostream from the inputstream%0A            AudioStream audioStream = new AudioStream(in);%0A%0A            // play the audio clip with the audioplayer class%0A            AudioPlayer.player.start(audioStream);
+Clip clip = AudioSystem.getClip();%0A            clip.open(audioInputStream);%0A            FloatControl gainControl =%0A                    (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);%0A            gainControl.setValue(gainControl.getMaximum());%0A            clip.start();%0A
 %0A   

add max gain to audio playback volume