1

Проигрываю аудио во фрагменте. Все воспроизводит, но хотела бы уточнить. Все ли правильно делаю. Т.е. с точки зрения траты ресурсов. После проигрывания аудио плеер нужно закрывать или нет?

public class ItemFragment extends Fragment {

    public static final String ARG_LETTER = "letter";
    public static final String ARG_DESCRIPTION = "description";
    public static final String ARG_IMAGE = "image";
    public static final String ARG_AUDIO = "audio";

    String mSound;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(
                R.layout.pager_item, container, false);
        Bundle args = getArguments();

        TextView txtLetter = (TextView) rootView.findViewById(R.id.txtLetter);
        ImageView imgLetter = (ImageView) rootView.findViewById(R.id.imgLetter);

        txtLetter.setText(args.getString(ARG_LETTER));
        imgLetter.setImageBitmap(getBitmapFromAssets(args.getString(ARG_IMAGE)));

        mSound = args.getString(ARG_AUDIO);

        play(mSound);

        imgLetter.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                play(mSound);
                return false;
            }
        });

        return rootView;
    }

    private Bitmap getBitmapFromAssets(String filename) {
        AssetManager assetManager = this.getContext().getAssets();
        Bitmap bitmap = null;
        try {
            InputStream in = assetManager.open("img/alphabet/" + filename);
            bitmap = BitmapFactory.decodeStream(in);
            return bitmap;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bitmap;
    }

    void play(String filename) {

        try {
            AssetFileDescriptor afd = this.getContext().getAssets().openFd("sound/alphabet/" + filename);
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mp.setLooping(false);
            mp.prepare();
            mp.start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.