因此,我正在为我的移动编程类(class)创建一个应用程序,但我在使用它的“播放”部分时遇到了困难。给你一些背景:基本上我们需要创建一个基本的音频播放器,它从预定义的源下载 mp3,然后播放该 mp3,等等。我已经正确设置了下载服务,但我很困惑为什么我的播放文件的代码不起作用。在我的 main.java 中,我有很多匿名信息。 UI 按钮的 onclick 监听器,然后是我的媒体播放器服务中的 switch 语句,以确定单击了哪个按钮。
这是我在主要 Activity 中对播放选项的点击:
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayService.class);
File path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, "Bob_Marley-Jammin.mp3");
intent.putExtra("path", file);
intent.putExtra("key", 0);
startService(intent);
}
});
点击下载:
download.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DownloadService.class);
intent.putExtra("url", "https://dl.dropbox.com/s/6e6pn43916nl10i/Bob_Marley-Jammin.mp3?dl=1");
startService(intent);
}
});
这是我的 PlayService:
package com.connor.black;
import java.io.IOException;
import android.app.IntentService;
import android.content.Intent;
import android.media.MediaPlayer;
public class PlayService extends IntentService{
public PlayService() {
super("PlayService");
}
public MediaPlayer mMediaPlayer;
public String path;
@Override
protected void onHandleIntent(Intent intent) {
path = intent.getStringExtra(path);
int key = intent.getIntExtra("key", 0);
mMediaPlayer = new MediaPlayer();
switch (key) {
case 0: //Play
if (mMediaPlayer.isPlaying())
break;
else{
try {
mMediaPlayer.setDataSource(path);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
mMediaPlayer.start();
}
break;
case 1: //Pause
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
break;
case 2: //Stop
if(mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
mMediaPlayer.seekTo(0);
}
break;
default:
break;
}
}
}
基本上文件下载是正确的,但是当我按下“播放”按钮时没有任何反应。
最佳答案
你的函数被调用了吗?使用 Log.d 检查。您的 mp3 路径是否正确?
以下小 fragment 播放 MP3(更改文件路径)
package com.aplayer;
import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
public class APlayerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MediaPlayer mMediaPlayer = new MediaPlayer();
Uri data;
data = Uri.parse("/sdcard/jazz.mp3");
mMediaPlayer = MediaPlayer.create(getBaseContext(), data);
mMediaPlayer.setLooping(false); // Set looping
mMediaPlayer.start();
}
关于android - 使用 MediaPlayer 服务播放下载的文件,Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10989168/