코딩하기/android studio

(android studio) 배경음 만들기 - bgm 넣기

치즈도넛 2021. 4. 3. 17:40
반응형

어플이 심심하지 않도록 bgm을 넣어주곤 하는데

 

제가 원하는 기능은 어플이 켜지자마자 음악이 나오고

어플을 종료하면 저절로 꺼지는 기능을 만들고자 했습니다.

 

 

우선 음악(.mp3)을 넣어야 합니다.

 

res > 우클 > new > Android Resource Directory

> Resource type을 raw로 바꿔줍니다.


raw에 음악 파일을 넣습니다(음악 파일의 이름은 소문자만 가능합니다.)

 

 

이제 음악 파일을 넣었으니 재생하는 코드를 만듭니다.

 

 


AndroidManifest

    <application
    
    <service android:name=".MusicService"></service>
    
     </application>

꼭 등록해야만 사용할 수 있습니다!!

 

 

MusicService.java

public class MusicService extends Service {
    MediaPlayer mediaPlayer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();

        mediaPlayer = MediaPlayer.create(this, R.raw.bluedream);
        mediaPlayer.setLooping(true); // 무한 루프
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mediaPlayer.start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mediaPlayer.stop();
        mediaPlayer.release();
        super.onDestroy();
    }
}

 

 

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        startService(new Intent(getApplicationContext(), MusicService.class));
   }
        
    @Override
    protected void onDestroy() {
        stopService(new Intent(getApplicationContext(), MusicService.class));
        super.onDestroy();
    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        //이벤트 작성
        // System.exit(0);
        stopService(new Intent(getApplicationContext(), MusicService.class));
    }

    @Override
    public void onBackPressed() {
        long curTime = System.currentTimeMillis();
        long gapTime = curTime - backBtnTime;

        if (0 <= gapTime && 2000 >= gapTime) {
            super.onBackPressed();
        } else {
            backBtnTime = curTime;
            Toast.makeText(this, "한번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT).show();
        }
        stopService(new Intent(getApplicationContext(), MusicService.class));
    }
}

onUserLeaveHint 부분이 없으면 홈화면으로 어플을 종료시켰을 때, 음악이 꺼지지 않습니다. 

그래서 홈화면을 막는다면 상관없지만 아니라면 필요한 부분입니다.

 

 

 

** onUserLeaveHint 때문에 intent를 할 때,

음악이 꺼지는 현상이 생겼습니다.

 

이것을 해결하는 방법은 intent를 하기전에

FLAG_ACTIVITY_NO_USER_ACTION를 넣어주면 해결됩니다.

Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.addFlags(FLAG_ACTIVITY_NO_USER_ACTION);
startActivity(intent);

 

 

 

모두 즐겁게 코딩하세요~

반응형