java - 当我单击android中的按钮时,我想一个接一个地播放音频
问题描述
ArrayList<String> videolist = new ArrayList<>();
videolist.add("http://muurl.com/abc/song1.mp3");
videolist.add("http://muurl.com/abc/song2.mp3");
videolist.add("http://muurl.com/abc/song3.mp3");
我已将音频链接存储在数组列表中。当我单击按钮时,我想一个接一个地播放该音频,当我单击按钮时,第二次音频应该从第一个音频链接开始
解决方案
结合OnCompletionListener查看MediaPlayer类:
你会做这样的事情:
int playListPos = 0; // declare this outside the button click probably as a global variable (so we can access it and increment in the on click listener of the button
// the below code should go inside the button click
String url = videolist.get(playListPos); // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
// this will be called every time a file is finished playing
if (videolist.size() < playListPos) { // let's see if there is more files to play
mediaPlayer.setDataSource(videolist.get(playlistPos));
mediaPlayer.prepare();
mediaPlayer.start();
playListPos++;
} else {
// we played until the end. reset to 0 for when button is clicked again to restart from the beginning
playListPos = 0;
}
});
mediaPlayer.start();
推荐阅读
- laravel-5 - 管理员创建用户,不希望用户在管理员使用 Laravel 的默认身份验证系统注册后自动登录
- c++ - 为什么 CoCreateInstance 可以在完全相同的上下文中返回两个不同的 HRESULT?
- css - 状态更改时如何将css文件从服务器添加到角度组件
- asp.net - 如何将 API 数据中的图形显示到 Umbraco?
- javascript - 未捕获的类型错误:document.getElementByTagName 不是函数
- firebase - 'eslint' 不是内部或外部命令、可运行程序或批处理文件
- graphql - GraphQL:如何让它返回一个灵活的动态数组,这取决于营销人员填写的内容?
- r - 强制 .GRP 计数器从 data.table 中的 2 而不是 1 开始
- javascript - 如何将 javascript 缓冲区转换为 c/c++ API 的字节数组?
- typescript - 打字稿:基于参数中存在的键的映射返回类型