• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Play sound from assets?

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
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones