i'm trying to add music to my game but it stops after

孤街醉人 提交于 2020-01-06 06:52:11

问题


so i am very new to scripting and this is my first application i build followed a tutorial but now i want to add music to it found a small code online but the music stops after 1 min while music should last 7 mins?

anyone here who can help me with this?

and also how could i make a song loop?

i did get this " MediaPlayer.setLooping(true); " but i don't know if it's gonna work so wanted to ask with this question too :p

Thanks already for you'r time.

i've looked for similar questions and used those answers but did not work, are i did implement it wrong since i am very new to this..

My Code.

package com.example.myapplication;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    Constants.SCREEN_WIDTH = dm.widthPixels;
    Constants.SREEN_HEIGHT = dm.heightPixels;


    setContentView(new GamePanel(this));





    MediaPlayer Music = MediaPlayer.create(MainActivity.this,R.raw.music);
    Music.start();
    MediaPlayer.setLooping(true);
}

}

I would like music to play and continuesly looping it does not need to stop.


回答1:


You need WakeLock or background service for playing music in sleep mode. I guess you can try keep your device alive (tap screen) and music would play.

1) Wakelock. Add permission to manifest

<uses-permission android:name="android.permission.WAKE_LOCK" />

And call on Create method:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);  
wakelock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getCanonicalName());
wakelock.acquire();

docs

2) Background service

docs

This is much more complicated, because you need to create notification etc. But you can try to follow android docs.

3) Read this doc. Here is guide with examples with wakelock and service.



来源:https://stackoverflow.com/questions/55406715/im-trying-to-add-music-to-my-game-but-it-stops-after

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!