Apps Play sound from assets?

GIR

Member
Feb 14, 2010
95
10
18
UK
realfred.uphero.com
I want to play a sound in an app im writing as part of my learning curve.

Im using eclipse on Ubuntu for 2.1, and have the track.ogg file in the assets directory.

How does one go about playing the track when the program starts?

I know its a combination of
Code:
 R.raw.soundfile
but Im unsure how this works if theres more than 1 sound file.

I found many conflicting samples of code online and id like clarification.
Some of the different ways of doing this include::

Code:
aPlayer.play(mContext, Uri.parse("android.resource://"+PACKAGE_NAME+"/"+R.raw.soundfile), false, AudioManager.STREAM_SYSTEM);

Code:
mSoundManager.addSound(1, R.raw.sound);

Code:
mp.setDataSource(PATH_TO_FILE);

Ive found some info at MediaPlayer | Android Developers, android.net.Uri) BUT i cant find any code samples for setDataSource
Any pointers?

Thanks in advance,
GIR
 
Would you be so kind and share your solution to the rest of the world?


Sure, I can now that I have my Ubuntu pc fresh back online :)

First I had to create a directory called 'raw' under 'res', and then paste in the track.ogg file.

This is all I entered into the .java file to make it play the track when the App starts:

Code:
MediaPlayer player = MediaPlayer.create(this, R.raw.track);
        try {
            player.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-ge
            e.printStackTrace();
        
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        player.start();
        
        
    }
Hope this helps,
GIR
 
MediaPlayer mp = new MediaPlayer();
AssetFileDescriptor descriptor = getAssets().openFd( FILE_NAME );
mp.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength() );
descriptor.close();

mp.prepare();
mp.start();

android API stinks, somebody should fired thous guys.