简体   繁体   中英

Getting input data from resource wav file in "raw" folder

I have been trying to read a buffer from the bytes of a wav file located in the raw folder using InputStream .

I think what I don't understand is how to give the correct location of the file. the wav file in the R resource is an int so I cannot just do:

InputStream is = new FileInputStream(R.raw.music);

because int is not acknowledged for FileInputStream .

basically my code is a modified version of something I found:

public void read(short[] musicin) {
    try {
        // Create a DataInputStream to read the audio data back from the saved file.
        InputStream is = new FileInputStream("R.raw.music");

        BufferedInputStream bis = new BufferedInputStream(is);

        DataInputStream dis = new DataInputStream(bis);

        int buffsize=512;

        // Read the file into the music array.
        int i = 0;

        while (i<buffsize&&dis.available() > 0) {
            musicin[i] = dis.readByte(); 
            i++;
        }

        // Close the input streams.
        dis.close();
    } catch (Throwable t) {
        Log.e("AudioTrack","Playback Failed");
    }
}

So how can I read from the raw folder?

In your activity class

Context c;
c=this;
new yourClass(c);

In your class

 public yourclass(Context context)
 {

InputStream in = context.getResources().openRawResource(R.raw.yourfilename); 
}

What I did was:

1- add this in the activity before the thread starts:

final Context con;
    con=this;

2- call the class in the thread

new Wav_File_Reader();

. . .

Wav_File_Reader.read(musicin,con);

2- modify my class to be static :

public static void read(short[] musicin, Context ctx ) {
    try {
    
    //  InputStream is = getBaseContext().getResources().openRawResource(R.raw.music);
        
    InputStream is = ctx.getResources().openRawResource(R.raw.music);
    BufferedInputStream bis = new BufferedInputStream(is);
    DataInputStream dis = new DataInputStream(bis);

    
    int buffsize=512;
    // Read the file into the music array.
    int i = 0;
    
    short in[]=new short[200000];
    
    //while (dis.available() > 0) {
    //while (i<buffsize&&dis.available() > 0) {
    while (i<200000&&dis.available() > 0) {
        //musicin[i] = dis.readByte(); 
        //in[i]=dis.readByte(); 
        in[i]=dis.readShort();
    i++;
    }

    // Close the input streams.
    dis.close(); 

    } catch (Throwable t) 
    {
    Log.e("AudioTrack","Playback Failed");
    }
    }

and I was able to read directly from the R.raw folder.

好吧,InputStream 实现从一开始就引人注目,将其更改为:

InputStream is = this.getResources().openRawResource(R.raw.music);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM