Question

I have a ListPreference set up, and it has four options. I was just wondering if it was possible to play a sound after selecting one of the options? I want to make something that will make a sound your ringtone after selecting it from the ListPreference, and I want a sample of the sound to play after selecting it. I don't want the sound to play from clicking a button after selecting the option from the ListPreference. I want it to play while the PreferenceScreen is open, right after the selection has been made.

Was it helpful?

Solution

Perhaps you could add a listener and in the callback read the sound file from the classpath to play it. I quickly hacked together an example (using Java7) to show an example of playing an audio file, hopefully it helps:

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Main {

    public static void main(String args[]) {
        Clip clip;
        try {
            clip = AudioSystem.getClip();
            AudioInputStream inputStream = AudioSystem.getAudioInputStream(
                    Main.class.getResourceAsStream("Morse.aiff"));
            clip.open(inputStream);
            clip.start();
            // optionally, sleep the thread for the duration of the audio clip, 
            // or else you may not hear it
            Thread.sleep(5000); 
        } catch (LineUnavailableException | UnsupportedAudioFileException | IOException | InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top