在 Android 中获取音频文件持续时间的最佳方法是什么?
我正在使用 SoundPool 来播放我的应用程序中的音频剪辑。一切都很好,但我需要知道剪辑播放何时完成。
目前,我通过使用 MediaPlayer 实例。这工作得很好,但为了获取持续时间而加载每个文件两次看起来很浪费。我可以粗略地计算自己知道文件长度的持续时间(可从 AssetFileDescriptor),但我仍然需要知道采样率和通道数。
我看到了该问题的两个潜在解决方案:
- 确定剪辑何时完成播放(使用 SoundClip 似乎不可能)。
- 有一个类可以仅加载音频文件的标头并为我提供采样率/通道数(理想情况下,还可以提供样本计数以获得准确的持续时间)。
有什么建议吗?
谢谢, Max
我目前使用的代码(工作正常,但对于目的来说相当沉重):
String[] fileNames = ...
MediaPlayer mp = new MediaPlayer();
for (String fileName : fileNames) {
AssetFileDescriptor d = context.getAssets().openFd(fileName);
mp.reset();
mp.setDataSource(d.getFileDescriptor(), d.getStartOffset(), d.getLength());
mp.prepare();
int duration = mp.getDuration();
// ...
}
顺便说一句,这个问题已经询问但没有得到答案。
I'm using a SoundPool to play audio clips in my app. All is fine but I need to know when the clip playback has finished.
At the moment I track it in my app by obtaining the duration of each clip using a MediaPlayer instance. That works fine but it looks wasteful to load each file twice, just to get the duration. I could roughly calculate the duration myself knowing the length of the file (available from the AssetFileDescriptor) but I'd still need to know the sample rate and the number of channels.
I see two potential solutions to that problem:
- Figuring out when a clip has finished playing (doesn't seem to be possible with SoundClip).
- Having a class which could load just the header of an audio file and give me the sample rate/number of channels (and, ideally, the sample count to get the exact duration).
Any suggestions?
Thanks,
Max
The code I'm using at the moment (works fine but is rather heavy for the purpose):
String[] fileNames = ...
MediaPlayer mp = new MediaPlayer();
for (String fileName : fileNames) {
AssetFileDescriptor d = context.getAssets().openFd(fileName);
mp.reset();
mp.setDataSource(d.getFileDescriptor(), d.getStartOffset(), d.getLength());
mp.prepare();
int duration = mp.getDuration();
// ...
}
On a side note, this question has already been asked but got no answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过此操作:
但我不确定这是否比现有代码更轻。
Did you try this:
But i am not exactly sure that this is lighter than exisiting code.
尝试 FFmpegMediaMetadataRetriever:
Try FFmpegMediaMetadataRetriever: