我想从许多片段布局中使用这个MediaPlayer方法。
如何解析原始资源?
public void playSound(Uri path) throws IOException{
MediaPlayer player;
player = new MediaPlayer();
try {
player.setDataSource(path.getPath(), path);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
player.prepare();
player.start();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp){
mp.release();
}
});
}
我目前正在从我的片段中使用它来解析原始目录中的mp3文件。
Btn_shou.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Uri path = null;
switch (tone.getCheckedRadioButtonId())
{
case R.id.radioTone1:
path = Uri.parse("android.resource://" +getActivity().getApplicationContext().getPackageName() +"/"+R.raw.shou1);
try {
playSound(path);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
break;
'path'变量存在问题。 Android抱怨它无法找到mp3文件。
我终于解决了这个问题:
创建单独的MediaPlayer类。
package com.example.FragmentTabsTutorial;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import java.io.IOException;
public class plaSnd {
public void playSound(Uri path, Context context) throws IOException {
MediaPlayer player;
player = new MediaPlayer();
try {
player.setDataSource(context, path);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
player.prepare();
player.start();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
}
2.。)从我的片段中我创建了一个对象到plaSnd()类:
final plaSnd pla = new plaSnd();
3.。)创建了一个存储上下文的变量:
final Context context = getActivity().getApplicationContext();
4.。)根据点击的按钮设置我的路径变量,然后在'plaSnd'类中解析'context'和'path'到我的playSound()方法:
Btn_o.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Uri path = null;
switch (tone.getCheckedRadioButtonId())
{
case R.id.radioTone1:
path = Uri.parse("android.resource://" +getActivity().getApplicationContext().getPackageName() +"/"+R.raw.o1);
try {
pla.playSound(path, context);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
break;
这对我有用,虽然我确信可能有更好的解决方案......
答案 0 :(得分:0)
尝试替换它:
player = new MediaPlayer();
用这个:
// context should be any context, e.g. your activity or getApplicationContext()
player = MediaPlayer.create(context, R.raw.shou1);