java - 选择ListPreference时播放声音

标签 java android audio listpreference

我设置了一个ListPreference,它有四个选项。我只是想知道选择其中一个选项后是否可以播放声音?我想制作一种可以使声音从ListPreference中选择出来后成为您的铃声的东西,并且希望在选择后播放声音的示例。我不希望从ListPreference中选择选项后单击按钮来播放声音。我希望在选择完后立即在PreferenceScreen打开时播放。

最佳答案

也许您可以添加一个侦听器,然后在回调中从类路径中读取声音文件以进行播放。我迅速地整理了一个示例(使用Java7)来显示播放音频文件的示例,希望它可以帮助您:

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);
        }
    }
}

关于java - 选择ListPreference时播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17584307/

相关文章:

java - ArrayList get 方法越界

android - InstallReferrerClient.startConnection() throwing 由 java.lang.SecurityException 引起

javascript - 音频持续时间返回 NaN

swift - 类型不符合协议(protocol) 'AVCaptureFileOutputRecordingDelegate'

java - 分配 APK android studio 时出错

java - 如何将 OWL API 对象转换为 Java 对象?

java - Checkstyle:访问变量名称?

android - java.lang.VerifyError : com/adobe/creativesdk/aviary/internal/account/BillingContentFactory 错误

java - Google map v2 - 用不同颜色绘制路线 - Android

java - 如何在 ListView 中向具有多个声音的Android onclick添加音频