java - 在应用程序启动时播放声音

标签 java android

如何让我的应用程序在启动时播放 mp3(在我的资源中)?或者,如果我希望在单击按钮时发生这种情况呢?

最佳答案

来自 Dev Guide 的音频和视频部分:

Perhaps the most common thing to want to do is play back media (notably sound) within your own applications. Doing this is easy:

  1. Put the sound (or other media resource) file into the res/raw folder of your project, where the Eclipse plugin (or aapt) will find it and make it into a resource that can be referenced from your R class

  2. Create an instance of MediaPlayer, referencing that resource using MediaPlayer.create, > and then call start() on the instance:

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();

To stop playback, call stop(). If you wish to later replay the media, then you must reset() and prepare() the MediaPlayer object before calling start() again. (create() calls prepare() the first time.)

To pause playback, call pause(). Resume playback from where you paused with start().

所以将上面的代码示例放在启动器 Activity 的 onCreate() 或 onStart() 中,让它在启动时播放,并将它放在按钮的 onClick() 方法中以响应按钮按下。

关于java - 在应用程序启动时播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4116345/

相关文章:

android - 如何使用 ADB 终止所有 Activity 任务/应用程序?

java - 有什么方法可以获取 XMLPullParser 函数的进度吗?

java - 设置 setMylocationenable(true) 时无法获取谷歌地图 fragment 中的 Activity 上下文

java - Java中不插入MySQL数据库

java - 在不重启服务器的情况下部署到 tomcat7

java - 如何从 JSON 设置数据?

java - 更新到 Android 4.4 KitKat 后无法找到 Movies 文件夹

java - SocketInitiator 的队列容量使用情况 (QuickFIX/J)

java - 如何在 System.in 上使用多个 Scanner 对象?

java - 带有RelativeLayout的ScrollView