jhi*_*hie 31 java media android background-music
你好!第一次在stackoverflow上问一个问题.精彩!哈哈.
我们正在开发Android游戏,我们为我们的介绍播放一些背景音乐(我们有一个简介活动),但我们希望它继续播放到下一个活动,也许能够从任何地方再次停止或播放音乐应用.
我们目前正在做的是在我们的Intro Activity中使用MediaPlayer播放bgm.但是,一旦用户离开该活动,我们就会停止播放音乐.我们是否必须使用像服务这样的东西?或MediaPlayer/SoundPool足够吗?如果有人知道答案,我们很高兴感谢您与我们分享.谢谢!
您还可以使用媒体播放器创建播放音乐的服务,如下所示.
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc); //OR stopService(svc);
Run Code Online (Sandbox Code Playgroud)
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
使用SoundPools或MediaPlayers创建静态SoundManager.
创建一个名为keepMusicGoing的静态标志.
创建第一个激活时启动音乐.
切换行为时,将keepMusicGoing设置为true.
在活动的onStop事件中检查keepMusicGoing是否为true,如果是,则保持音乐开启,然后将keepMusicGoing设置为false.
如果他们按下主页按钮,则keepMusicGoing标志将为false,因此当活动失去焦点时音乐将停止.
给我发电子邮件,我可以发给你一些我写过的SoundManagers使用MediaPlayers和其他SoundPools
乍得
如果我正确理解你的情况,那么我已经遇到过几次同样的问题了。我正在使用不同的线程在我的应用程序中播放音乐。此实现传递了对上下文的静态引用,我知道该上下文在播放音乐时将处于活动状态。
public class AudioPlayer extends Thread {
private Context c;
private Thread blinker;
private File file;
public AudioPlayer (Context c, File file) {
this.c = c;
this.file = file;
}
public void go () {
blinker = this;
if(!blinker.isAlive()) {
blinker.start();
}
}
public void end () {
Thread waiter = blinker;
blinker = null;
if (waiter != null)
waiter.interrupt ();
}
public void run () {
MediaPlayer ap = MediaPlayer.create(c, Uri.fromFile(file));
int duration = ap.getDuration();
long startTime = System.currentTimeMillis();
ap.start();
try {
Thread thisThread = Thread.currentThread();
while (this.blinker == thisThread && System.currentTimeMillis() - startTime < duration) {
Thread.sleep (500); // interval between checks (in ms)
}
ap.stop ();
ap.release ();
ap = null;
} catch (InterruptedException e) {
Log.d("AUDIO-PLAYER", "INTERRUPTED EXCEPTION");
ap.stop ();
ap.release();
ap = null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30271 次 |
| 最近记录: |