是否有可能将位于应用程序原始文件夹中的 mp3 文件设置为 ExoPlayer?
不幸的是,我尝试使用以下代码片段来实现它,但没有成功:
mMediaPath = "android.resource://" + getPackageName() + File.separator + R.raw.ringtone;
任何帮助是极大的赞赏!
可以从原始文件夹加载文件,关键是使用RawSourceDataSource
.
LoopingMediaSource
这是一个在原始目录中为 mp3 文件创建一个示例(在 Kotlin 中) :
val uri = RawResourceDataSource.buildRawResourceUri(R.raw.mp3file) val dataSource = RawResourceDataSource(this) dataSource.open(DataSpec(uri)) val source = ExtractorMediaSource(uri, DataSource.Factory { dataSource }, Mp3Extractor.FACTORY, null, null) LoopingMediaSource(来源)
我无法从原始文件加载 mp3 文件,因此根据与 ExoPlayer 的一位作者的讨论,我最终将它们移动到 assets 目录。(https://github.com/google/ExoPlayer/issues/556)
如果将来有人需要它,这就是我从资产中访问 mp3 文件的方式:
mMediaPath = "asset:///my_ringtone.mp3";
并将此路径添加到 DemoPlayer 中,如下所示:
new DemoPlayer(new ExtractorRendererBuilder(this, userAgent, Uri.parse(mMediaPath), null, new Mp3Extractor()));
感谢所有愿意回答我问题的人。
这个库的文档太糟糕了。我花了几个小时来编写一个简单的功能。如果有人有兴趣,此代码有效:
public static void playSound(Context context, int sounRes, float volume)
{
//example int sounRes=R.raw.duck;
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);
DataSpec dataSpec = new DataSpec(RawResourceDataSource.buildRawResourceUri(sounRes));
final RawResourceDataSource rawResourceDataSource = new RawResourceDataSource(context);
try {
rawResourceDataSource.open(dataSpec);
} catch (RawResourceDataSource.RawResourceDataSourceException e) {
e.printStackTrace();
}
DataSource.Factory factory = () -> rawResourceDataSource;
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource
.Factory(factory)
.createMediaSource(rawResourceDataSource.getUri());
player.prepare(mediaSource);
player.setPlayWhenReady(true);
player.setVolume(volume);
player.addListener(new Player.EventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_ENDED) {
player.release();
}
}
});
}
如果要使用资产文件,请使用:
public static void playSound(Context context,String audioPath,float volume)
{
//example String audioPath = "duck.mp3";
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "exoPlayerSample"));
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource
.Factory(dataSourceFactory)
.createMediaSource(Uri.parse("asset:///" + audioPath));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
player.setVolume(volume);
player.addListener(new Player.EventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if(playbackState == Player.STATE_ENDED){
player.release();
}
}
});
}