0

I've used the code from this existing post to play an MP3 file:

package com.mjr.testsound

import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

            if (savedInstanceState == null) {
                val mp: MediaPlayer = MediaPlayer.create(applicationContext, R.raw.guitar3)
                mp.start()
            }

        setContentView(R.layout.activity_main)
    }
}

The weird thing is that it cuts out after a second if it's played in the MAIN startup activity, but it works fine if played in a second activity. Any idea what's happening?

Also I know that the activity is not terminating, I've logged the activity lifecycle and the cut out happens well before OnPause is logged.

Matthew
  • 31
  • 5
  • Are you navigating from the first activity to another activity as soon as the first activity opens up ? – Nisanth Reddy May 11 '21 at 11:04
  • Since this is a question where 2 activities need comparing it would be helpful to add the relevant code from each activity. Not just the mp3 init code. – froy001 May 11 '21 at 11:13
  • I've updated the original post's code with literally all the only extra code I have inserted in the OnCreate method of the MainActivity of a completely new empty project. The problem still occurs – Matthew May 12 '21 at 12:51

1 Answers1

0

I had similar problems last week when implementing a media player. You have to be careful to start it correctly and release the resources.

In combination with a CompletionListener I got a working solution. Before that, I had non-reproducible failures.

I have packed the whole thing into the method playSound(). This method gets called in an onClick event, if one of my buttons is clicked.

Mediaplayer is first initialised in the activity with:

MediaPlayer soundTest = null; 

related method:

    public void playSound() {

    try {

        if (soundTest != null){
            soundTest.reset();
            soundTest.release();
            soundTest = null;
        }
        soundTest = MediaPlayer.create(this, R.raw.coins);

        soundTest.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mp != null) {
                    mp.reset();
                    mp.release();
                    soundTest = null;
                }
            }
        });
        soundTest.start();

    } catch (Exception e) {

        e.printStackTrace();
    }
}

Maybe this helps you.

Dorian Feyerer
  • 258
  • 5
  • 14