w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Playing a sentence in android MediaPlayer

This code worked for me:

package com.example.ouio;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;

public class MainActivity extends Activity {

    private MediaPlayer mPlayer;
    private List<String> mQueuedFiles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onStart() {
        super.onStart();
        mPlayer = new MediaPlayer();
        mPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                System.out.println("OnCompletion called");
                playNextFile();
            }
        });
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                System.out.println("MediaPlayer error: " + what + " " +
extra);
                mPlayer.release();
                mPlayer = new MediaPlayer();
                return false;
            }
        });
    }

    public void onStop() {
        super.onStop();
        mPlayer.release();
    }

    private AssetFileDescriptor getFileForWord(String word) {
        int sound_id = getResources().getIdentifier(word, "raw",
getPackageName());

        return getResources().openRawResourceFd(sound_id);
    }

    private void playSentence(List<String> words) {
        mQueuedFiles = new ArrayList<String>();

        for (int i = 0; i < words.size(); i++) {
            mQueuedFiles.add(i, words.get(i));
        }

        playNextFile();     
    }

    private void playNextFile() {
        if (mQueuedFiles.size() == 0) {
            return;
        }

        AssetFileDescriptor afd = getFileForWord(mQueuedFiles.get(0));
        mQueuedFiles.remove(0);
        try {
            mPlayer.reset();
            mPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
            mPlayer.prepare();
            mPlayer.start();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.