在片段内使用Mediaplayer [英] Using Mediaplayer within a Fragment

查看:86
本文介绍了在片段内使用Mediaplayer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在尝试理解片段及其工作方式.我有一个使布局夸大的片段.按按钮时,我试图播放声音,但遇到媒体播放器的一些问题.

I'm still trying to understand fragments and how they work. I have a fragment that inflates a layout. I am trying to play a sound when a button is pushed but I am coming across some problems with the mediaplayer.

代码是:

private void playSound(int resId) {
    MediaPlayer mp = MediaPlayer.create(Tab1Fragment.this, resId);
    mp.setOnCompletionListener(Tab1Fragment.this);
    mp.start();
}

错误是: MediaPlayer类型的create(Context,int)方法不适用于参数(Tab1Fragment,int)

我尝试使用 getApplicationContext()无济于事.

感谢您的帮助谢谢

推荐答案

在您的片段类的onCreateView方法中使用此代码,它将可以正常工作.

Use this code in onCreateView method of your fragment class and it will be working fine.

mp = MediaPlayer.create(getActivity, R.raw.songname);

现在,您可以在按钮单击侦听器上将其称为start方法.确保将 MediaPlayer mp; 设为片段类的全局变量,以便以后使用.

Now you can call it's start method on your button click listener. Make sure to make the MediaPlayer mp; global for fragment class so you can use it afterwards.

这篇关于在片段内使用Mediaplayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆