SePröbläm
SePröbläm

Reputation: 5739

libGDX/Android: How to loop background music without the dreaded gap?

I'm using libGDX and face the problem that background music does not flawlessly loop on various Android devices (Nexus 7 running Lollipop for example). Whenever the track loops (i.e. jumps from the end to the start) a clearly noticeable gap is hearable. Now I wonder how the background music can be played in a loop without the disturbing gap?

I've already tried various approaches like:

Any ideas what's wrong with the code snippet?

Upvotes: 5

Views: 1914

Answers (2)

SteveL
SteveL

Reputation: 3389

This is an old question but I will give my solution in case anyone has the same problem.

The solution requires the use of the Audio-extension(deprecated but works just fine),if you cant find the link online here are the jars that I am using, also requires some external storage space.

The abstract is the following

  1. Extract the raw music data with a decoder(VorbisDecoder class for ogg or Mpg123Decoder for mp3)and save them to the external storage(you can make a check to see if it already exists so that it only needs to be extracted once, cause it takes some time).
  2. Create a RandomAccessFile using the file you just saved to the external storage
  3. While playing set the RandomAccessFile pointer to the correct spot in the file and read a data segment
  4. Play the above data segment with the AudioDevice class

Here is some code

Extract the music file and save it to the external storage,file is the FileHandle of the internal music file,here is an ogg and thats why we use VorbisDecoder

    FileHandle external=Gdx.files.external("data/com.package.name/music/"+file.name());
    file.copyTo(external);
    VorbisDecoder decoder = new VorbisDecoder(external);
    FileHandle extreactedDataFile=Gdx.files.external("data/com.package.name/music/"+file.nameWithoutExtension()+".mdata");
    if(extreactedDataFile.exists())extreactedDataFile.delete();
    ShortBuffer sbuffer=ByteBuffer.wrap(shortBytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    while(true){
        if(LogoScreen.shouldBreakMusicLoad)break;
        int num=decoder.readSamples(samples, 0,samples.length);
        sbuffer.put(samples,0,num);
        sbuffer.position(0);
        extreactedDataFile.writeBytes(shortBytes,0,num*2, true);
        if(num<=0)break;
    }
    external.delete();

Create an RandomAccessFile pointing to the file we just created

    if(extreactedDataFile.exists()){
        try {
            raf=new RandomAccessFile(Gdx.files.external(extreactedDataFile.path()).file(), "r");
            raf.seek(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Create a Buffer so we can translate the bytes read from the file to a short array that gets feeded to the AudioDevice

public byte[] rafbufferBytes=new byte[length*2];
public short[] rafbuffer=new short[length];
public ShortBuffer sBuffer=ByteBuffer.wrap(rafbufferBytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();

When we want to play the file we create an AudioDevice and a new thread where we read constantly read from the raf file and feed it to the AudioDevice

    device = Gdx.audio.newAudioDevice((int)rate/*the hrz of the music e.g 44100*/,isthemusicMONO?);
    currentBytes=0;//set the file to the beggining
    playbackThread = new Thread(new Runnable() {
        @Override
        public synchronized  void run() {
                while (playing) {
                        if(raf!=null){
                            int length=raf.read(rafbufferBytes);
                            if(length<=0){
                                ocl.onCompletion(DecodedMusic.this);
                                length=raf.read(rafbufferBytes);
                            }
                            sBuffer.get(rafbuffer);
                            sBuffer.position(0);
                            if(length>20){
                                try{
                                    device.writeSamples(rafbuffer,0,length/2);
                                    fft.spectrum(rafbuffer, spectrum);
                                    currentBytes+=length;
                                }catch(com.badlogic.gdx.utils.GdxRuntimeException ex){
                                    ex.printStackTrace();
                                    device = Gdx.audio.newAudioDevice((int)(rate),MusicPlayer.mono);
                                }
                            }
                        }
                    }
                }
    });
    playbackThread.setDaemon(true);
    playbackThread.start();

And when we want to seek at a position

public void seek(float pos){
    currentBytes=(int) (rate*pos);
    try {
        raf.seek(currentBytes*4);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Upvotes: 0

SePr&#246;bl&#228;m
SePr&#246;bl&#228;m

Reputation: 5739

Just for the records: It tuned out to be unsolvable. At the end, we looped the background music various times inside the file. This way the gap appears less frequently. It's no real solution to the problem, but the best workaround we could find.

Upvotes: 3

Related Questions