Android Assets-Folder:它始终按字母顺序获取第一个文件

发布于 2024-09-28 05:00:53 字数 772 浏览 2 评论 0原文

我是 Java/Android 编程新手,所以请耐心等待。

我尝试播放位于 asset 文件夹中的 mp3。我知道 /res/raw/ 文件夹还有另一种方法,但使用资产文件夹,因为稍后我将尝试通过字符串访问该文件。

此代码可以播放 mp3 文件:

        try
    {
        MediaPlayer mp = new MediaPlayer(); 
        FileDescriptor sfd = getAssets().openFd("song.mp3").getFileDescriptor(); 


        mp.setDataSource(sfd); 
        mp.prepare(); 
        mp.start();
    }
    catch(Exception e) {}

现在的问题是:在同一个资产文件夹中存储了另一个 mp3 文件。虽然我指定了要使用的 mp3 的名称,但它采用字母表中第一个的名称。例如,另一个文件名为“music.mp3”,它会播放这个文件。将其重命名为“worldmusic.mp3”它将播放“song.mp3”。将“worldmusic.mp3”重命名回“music.mp3”,它将再次使用此 mp3。另一个测试:将“song.mp3”重命名为其他名称,以便应用程序可以找到上面代码指定的内容,这将导致不播放任何歌曲。所以这意味着歌曲名必须存在,尽管它在字母表中任意选取歌曲。

我正在使用eclipse的AVD模拟器进行测试。但我认为在真实设备上的行为是相同的。

有人对这个问题有想法吗?

I'm new in Java/Android programming, so please have patience with me.

I try to play a mp3 which is locate und the assets folder. I know there is another way with the /res/raw/ folder, but use the assets-folder because later I'll try to access the file by String.

This code works to play a mp3-file:

        try
    {
        MediaPlayer mp = new MediaPlayer(); 
        FileDescriptor sfd = getAssets().openFd("song.mp3").getFileDescriptor(); 


        mp.setDataSource(sfd); 
        mp.prepare(); 
        mp.start();
    }
    catch(Exception e) {}

Now the problem: In the same assets-folder is another mp3 file stored. Though I specify the name of the mp3 to use it take the one which comes first in alphabet. E.g. the other file is named "music.mp3" it plays this one. Renaming it to "worldmusic.mp3" it will play "song.mp3". Rerename "worldmusic.mp3" back to "music.mp3" it will take this mp3 again. Another test: Renaming "song.mp3" to something other so the application can find whats specify by the code above will result that no song is played. So this means the songname have to exist, although it take arbitrary the song first in alphabet.

I'm testing with the AVD emulator of eclipse. But I think the behaviour would be the same on a real device.

Have someone an idea about this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兰花执着 2024-10-05 05:00:53

我不认为使用 FileDescriptor 是执行此操作的正确方法。尝试使用 .create() 和 Uri 代替:

MediaPlayer mp = MediaPlayer.create(getBaseContext(), songUri);
mp.start();

I don't believe using FileDescriptor is the right way to do this. Try using .create() and a Uri instead:

MediaPlayer mp = MediaPlayer.create(getBaseContext(), songUri);
mp.start();
世界如花海般美丽 2024-10-05 05:00:53

不知道为什么,但 URI 语法似乎不适用于资产。尝试获取 AssetFileDescriptor,如相关问题中的回答:

从资产目录

Not sure why, but the URI syntax doesn't seem to work for the assets. Try getting the AssetFileDescriptor instead, as answered in the related question:

Play audio file from the assets directory

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文