Using a buffer with Android AudioTrack

后端 未结 2 982
清歌不尽
清歌不尽 2021-02-02 01:36

I\'m trying to figure how I would use a buffer with AudioTrack to effectively stream music. I know you can queue audio using the write method but once the audio is queued how do

2条回答
  •  北海茫月
    2021-02-02 02:02

    *This code will help to play audio with buffer*

      private void PlayShortAudioFileViaAudioTrack(String filePath) throws IOException
        {
    
        // We keep temporarily filePath globally as we have only two sample sounds now..
    
        if (filePath==null)                                                                     
        return;
    
        //Reading the file..
    
        byte[] byteData = null; 
        File file = null; 
        file = new File(filePath); 
    
        // for ex. path= "/sdcard/samplesound.pcm" or "/sdcard/samplesound.wav"
    
        byteData = new byte[(int) file.length()];
        FileInputStream in = null;
         try {
        in = new FileInputStream( file );
         in.read( byteData );
         in.close(); 
        } catch (FileNotFoundException e) {
    
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        // Set and push to audio track..
    
        int intSize = android.media.AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
        AudioFormat.ENCODING_PCM_8BIT); 
        AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
        AudioFormat.ENCODING_PCM_8BIT, intSize, AudioTrack.MODE_STREAM); 
        if (at!=null) { 
        at.play();
    
        // Write the byte array to the track
    
    at.write(byteData, 0, byteData.length); 
        at.stop();
        at.release();
        }
        else
         Log.d("TCAudio", "audio track is not initialised ");
         }
    

提交回复
热议问题