播放资产目录中的音频文件 [英] Play audio file from the assets directory

查看:48
本文介绍了播放资产目录中的音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");播放器 = 新媒体播放器();player.setDataSource(afd.getFileDescriptor());玩家准备();播放器开始();

问题在于,当我运行此代码时,它开始按字母顺序播放资产目录中的所有音频文件,而不是仅播放我请求的音频文件.我究竟做错了什么?有没有更好的方法来播放资产目录中的音频文件?

后续问题:将音频文件保存在 assets 目录中和将它们保存在 res/raw 目录中有区别吗?此外,如果它们位于资产目录中,则它们不会获得 id.如果我将音频文件移动到 res/raw 文件夹,那么我在重用 MediaPlayer 时会遇到问题,因为 setDataSource() 没有 id 参数.我找不到处理此类问题的好的指南.

解决方案

player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());

<块引用>

如果您的资产中只有一个文件,您的版本就可以使用目录.资产目录内容实际上不是真实文件"磁盘上.所有这些都一个接一个地放在一起.所以,如果你这样做不指定从哪里开始以及读取多少字节,播放器将读到最后(即,将继续播放资产中的所有文件目录)

I have the following code:

AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.start();

The problem is that, when I run this code, it starts playing all the audio files in the assets directory, in alphabetical order instead of just playing the audio file I requested. What am I doing wrong? Is there a better way to play audio files from the assets directory?

Follow-up question: Is there a difference between keeping audio files in the assets directory and keeping them in the res/raw directory? Besides the fact that they don't get ids if they are in the assets directory. If I move the audio files to the res/raw folder then I have a problem with reusing MediaPlayers because there is no id parameter for setDataSource(). I can't find a good guideline for handling this kind of problem.

解决方案

player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());

Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

这篇关于播放资产目录中的音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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