【问题标题】:Android Random Background Image with background sound带有背景声音的 Android 随机背景图像
【发布时间】:2018-02-12 20:49:44
【问题描述】:

我有一个 Activity,如果打开它,它会显示随机背景。

我想知道在 android 中是否可以使用有声音的背景。 就像背景是 Nature.jpg 那么背景音频是 BirdsChirping.mp3。 (所以它与背景的氛围相匹配。)

像这样:

> Nature.jpg = BirdsChirping.mp3 
> Ocean.jpg = Waves.mp3 
> Plane.jpg = JetEngineSound.mp3

这是我当前的代码:

//  RANDOM IMAGE
    int[] photos={R.drawable.nature, R.drawable.ocean};
    ImageView image= (ImageView) findViewById(R.id.main_activity_bg);
    Random ran=new Random();
    int i=ran.nextInt(photos.length);
    image.setImageResource(photos[i]);

【问题讨论】:

  • 我们真正的问题是什么?您希望我们帮助您编写在 Android 中运行声音的代码吗?
  • 请。根据显示的背景运行特定的声音。
  • 请检查我的答案并尝试一下,然后告诉我它是否有效

标签: android audio random background mp3


【解决方案1】:

首先,将您的 mp3 文件放在名为 raw 的目录中,然后使用您的所有 mp3 文件 ID 创建一个名为 sound 的数组。这个数组的大小应该和photos数组的大小一样,顺序也一样,这样photos数组的第一个文件就和sounds数组的第一个文件对应,如下代码:

int[] photos={R.drawable.nature, R.drawable.ocean};
int[] sounds={R.raw.BirdsChirping, R.raw.Waves};

然后要播放你需要使用的声音MediaPlayer

final MediaPlayer mp = MediaPlayer.create(this, sounds[i]);

这是初始化 MediaPlayer 的方法。 MediaPlayer 遵循静态工厂方法设计模式。为了获得一个实例,我们调用它的 create() 方法并将我们想要播放的声音的上下文和资源 ID 传递给它。

mp.start();

要播放声音,我们调用 MediaPlayer 的 start() 方法。此方法开始播放声音。

    int[] photos={R.drawable.nature, R.drawable.ocean};
        int[] sounds={R.raw.BirdsChirping, R.raw.Waves};
        ImageView image= (ImageView) findViewById(R.id.main_activity_bg);
        Random ran=new Random();
        int i=ran.nextInt(photos.length);
        image.setImageResource(photos[i]);
final MediaPlayer mp = MediaPlayer.create(this, sounds[i]);
        mp.start();

当某张照片在背景中随机设置时,这就是您的完整代码应该如何播放某种声音。

【讨论】:

  • 哇! @EyadMhanna!谢谢!这就是我要找的!到目前为止,您的答案是我在 Stack 中遇到的最流畅、最容易理解的答案。详细的分步教程,底部有完整的答案。我希望你能再次光临我未来的问题。赞一个!
  • @GoodbyeWorld 非常感谢您的客气话,很高兴我的回答对您有所帮助。非常感谢您的支持和回答接受。快乐编码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 2013-06-21
相关资源
最近更新 更多