Search code examples
androidaudio

How to code Audio in app?


Some Background

The app that i have made, is an interval app. This allows the user to choose the amount of time for each of the two intervals. When run, the app runs a countdown timer with the two user chosen time settings. I have two songs that i want to play for each interval, but i cant set the specific times when the song changes, because the user changes that. So if the user only picks 4 seconds for the first interval, I need the song to play for only that time, and when the countdown starts over with the other interval, I need the other song to play.

Now to my real question.

How do i call the audio to play? Ive looked at many questions, but they all say that i need to put the audioplayer in a new activity? If I put it in a new activity, will it not stop the countdown timer? How can i make it so that the countdown timer continues to run?


Solution

  • You have two methods to play sounds in android, one is SoundBoard (designed for short clips, don't use this if you want to play a song), the other one is MediaPlayer. You can play the audio by putting the file in the raw folder and then doing the following:

    MediaPlayer mp = MediaPlayer.create(ClassName.this, R.raw.sound); 
    mp.start();  
    

    Then when the timer ends you can stop the song with mp.stop(); and you can play the following audio file by doing:

    mp.reset();  
    mp = MediaPlayer.create(ClassName.this, R.raw.sound2);  
    

    When you finished remember to release the Mediaplayer with mp.release();.

    I hope I understood what you need to do, you should also put the mediaplayer inside a new thread, see this from the official android developers documentation:

    To avoid hanging your UI thread, spawn another thread to prepare the MediaPlayer and notify the main thread when done. However, while you could write the threading logic yourself, this pattern is so common when using MediaPlayer that the framework supplies a convenient way to accomplish this task by using the prepareAsync() method. This method starts preparing the media in the background and returns immediately. When the media is done preparing, the onPrepared() method of the MediaPlayer.OnPreparedListener, configured through setOnPreparedListener() is called.