这是我的应用程序的工作方式:
应用程序收到音乐后,它会先将文件保存到 SD 卡中,然后播放。我尝试使用由类(不是活动,而是处理程序)调用的异步任务来播放音乐。但是,音乐只能播放 1-2 秒。下面是 AsyncTask 的回调代码:
fos = new FileOutputStream(file);
fos.write(receivedMusicPayload);
fos.flush();
fos.close();
PlayMusicManager pmm = new PlayMusicManager(qrC);
pmm.execute();
这是玩家管理器:
public class PlayMusicManager extends AsyncTask<Void, Void, Void> {
private QRConnection qrC;
public PlayMusicManager(QRConnection qrC) {
this.qrC = qrC;
}
@Override
protected Void doInBackground(Void... params) {
MediaPlayer mediaPlayer = new MediaPlayer();
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "music.mid");
if (file.exists()) // check if file exist
{
FileInputStream fis;
try {
fis = new FileInputStream(file);
FileDescriptor fd = fis.getFD();
mediaPlayer.setDataSource( fd);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
qrC.getQrActivity().showResult("No such file");
}
return null;
}
@Override
protected void onPostExecute(Void parms) {
qrC.getQrActivity().showResult("Music Done.");
}
谢谢你的帮助!