Skip to main content

Playing wav File in android using Audio Track

To play a wav file read the wav file and pass the bytes to audio track chunck by chunk.

private void playWaveFile(){
       
        // define the buffer size for audio track
        int minBufferSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
        int bufferSize = 512;
        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
        String filepath = "File Path";

        int count = 0;
        byte[] data = new byte[bufferSize];
        try {
            FileInputStream fileInputStream = new FileInputStream(filepath);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);
            audioTrack.play();
           
            while((count = dataInputStream.read(data, 0, bufferSize)) > -1){
                audioTrack.write(data, 0, count);
            }
            audioTrack.stop();
            audioTrack.release();
            dataInputStream.close();
            fileInputStream.close();
       
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Comments

Popular posts from this blog

Adding Call log entries in Native Call Logs

While adding call logs we can set number in CallLog.Calls.NUMBER field , same for date  and duration. CallLog.Calls.CACHED_NAME will be filled with the cached name in case if the number is already saved in Contacts database. ContentValues values = new ContentValues(); values.put(CallLog.Calls.NUMBER, number); values.put(CallLog.Calls.DATE, System.currentTimeMillis()); values.put(CallLog.Calls.DURATION, 0); values.put(CallLog.Calls.TYPE, CallLog.Calls.OUTGOING_TYPE); //Type of call Outgoing/Incoming/Missed etc values.put(CallLog.Calls.NEW, 1); values.put(CallLog.Calls.CACHED_NAME, ""); values.put(CACHED_NUMBER_TYPE, 0); values.put(CACHED_NUMBER_LABEL, ""); this.getContentResolver().insert(CallLog.Calls.CONTENT_URI, values); Below Permissions are required to add call logs , add it in Manifest file, <uses-permission android:name="android.permission.WRITE_CALL_LOG"></uses-permission> <uses-permission android:name="android.perm...