6

I store all my sounds in the res folder. I'm wondering if there is a way to store them in the assets folder and play them from there?

This is the code I'm using now:

void StartSound(int id) {
    if (id==0)
        return;

    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    // float volume = actualVolume / maxVolume;
    float volume=(float) ( .01*(double)cGlobals.iVol);

    // Is the sound loaded already?
    if (nLastSound!=0)
        soundPool.stop(nLastSound); 

    int t=soundPool.play(id, volume, volume, 1, 0, 1f);
    nLastSound=t;
}

I want to change this to avoid a memory error when the APK tries to load. If I remove some of the files from the res folder it works fine. I'm hopping I want have the same issue if they are saved as a file.

4

4 回答 4

13

你也可以用另一种方式来做。将 .mp3 文件放在 res/Raw 文件夹下并使用以下代码:

MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.android);
mediaPlayer.start();
于 2013-05-28T17:20:56.243 回答
8
private void startSound(String filename){
    AssetFileDescriptor afd = getAssets().openFd(filename);
    MediaPlayer player = new MediaPlayer();
    player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    player.prepare();
    player.start();
}
于 2013-05-28T15:55:28.813 回答
3

您可以使用以下代码在您的资产文件夹中播放特定的音频文件(即your_file.mp3):

MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor afd = context.getAssets().openFd("your_file.mp3");
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
mediaPlayer.start();

并播放原始资源文件(即your_file):

MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.your_file));                    
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
mediaPlayer.start();
于 2016-11-28T18:44:14.730 回答
0

在此处输入图像描述

启动声音

startSound("mp3/ba.mp3");

方法

private void startSound(String filename) {
    AssetFileDescriptor afd = null;
    try {
        afd = getResources().getAssets().openFd(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    MediaPlayer player = new MediaPlayer();
    try {
        assert afd != null;
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        player.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    player.start();
}
于 2019-03-26T12:41:01.487 回答