-1

我正在使用下面的代码在 2 分钟后收到一条敬酒消息,同时我想用它添加一个声音警报。

Calendar cal = Calendar.getInstance();
     cal.get(Calendar.DATE);
     cal.add(Calendar.MINUTE,2);
     Intent intent = new Intent(this, MyBroadcastReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

            alarmManager.set(AlarmManager.RTC_WAKEUP,  cal.getTimeInMillis()
                , pendingIntent);

            Toast.makeText(this, "Time to get",
                    Toast.LENGTH_LONG).show();  

我尝试使用以下代码:

int icon = R.drawable.ic_launcher;        // icon from resources
            CharSequence tickerText = "Hello";              // ticker-text
            long when = cal.getTimeInMillis();        // notification time
            Context context = getApplicationContext();      // application Context
            CharSequence contentTitle = "My notification";  // message title
            CharSequence contentText = "Hello World!";      // message text

            Intent notificationIntent = new Intent(this, MyBroadcastReceiver.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 12345, notificationIntent, 0);

            // the next two lines initialize the Notification, using the configurations above
            Notification notification = new Notification(icon, tickerText, when);
            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
            notification.defaults |= Notification.DEFAULT_SOUND;
4

1 回答 1

0

你可以使用SoundPool类,像这样:

    private SoundPool soundPool;
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundPoolMap = new HashMap<Integer, Integer>();
    //Put your sounds here, from raw resources
    soundPoolMap.put(SOUND_SCHIVATO, soundPool.load(ctx, R.raw.schivato, 1));
    soundPoolMap.put(SOUND_GONG, soundPool.load(ctx, R.raw.gong, 1));
    soundPoolMap.put(SOUND_AHH, soundPool.load(ctx, R.raw.ahhh, 1));
    ...

    private void playSound(int sound) {
        /* Volume calculations */
        AudioManager mgr = (AudioManager) ctx
                .getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = streamVolumeCurrent / streamVolumeMax;

        /* Play the sound with the correct volume */
        soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);
}

在我的项目中,我创建了一个类来管理所有包含我发布的片段的音频通知。这个类非常简单,它只加载我的自定义声音HashMap并公开公共方法来播放它们。

Context需要加载 SounPool 的资源。这里有一个简单的教程

于 2012-08-31T13:31:39.013 回答