ZhouWeikuan / cocos2d

cocos2d for android, based on cocos2d-android-0.82, and now ported from cocos2d-iphone 0.99.4. The googlecode address is here: http://code.google.com/p/cocos2d-android-1/ . There are several demos to watch.
610 stars 291 forks source link

Request: Load Sounds from Assets or SDCard #34

Open dustinanon opened 13 years ago

dustinanon commented 13 years ago

Right now it seems that we can only load sounds from the res folder, and that is a major inconvenience for my work. I've tried to roll my own SoundManager, but there is something that I'm not grasping about loading from those two places.

If someone more skilled than myself could expand the functionality of SoundManager to support Assets and SDCard I would be greatly appreciative!

shashachu commented 13 years ago

Both SoundPool and MediaPlayer have methods that take in FileDescriptors.

For the assets directory, it will look something like this:

AssetFileDescriptor d = context.getAssets().openFd(filename); mAudioPlayer = new MediaPlayer(); // Need to use this version of setDataSource or else getDuration returns the wrong value. mAudioPlayer.setDataSource(d.getFileDescriptor(), d.getStartOffset(), d.getLength());

For the SD card, I believe you can do something like: File sdcard = Environment.getExternalStorageDirectory(); File file = new File(sdcard, path); FileInputStream stream = new FileInputStream(file); FileDescriptor fd = stream.getFD();

And then pass in the FileDescriptor to MediaPlayer.setDataSource or SoundPool.load().

Out of curiosity, why don't you want to use the res folder?

dustinanon commented 13 years ago

I have a bunch of data that will be loaded dynamically, so it won't be packaged with my application, but usually downloaded from the internet, stored to the SDCard, and loaded by the application.

As for assets, sometimes I will need to make special packages for different clients, in these cases it's impractical to ask them to download their data from the internet. It's also impractical for me to put the sounds into the res folder and custom hardcode references to the sounds for each client. So the solution would be to put the sounds/images that I need into the assets folder and access it that way.

If I was just making a game, then it'd be easy :)