gpt4 book ai didi

Android:媒体文件从文件系统中消失

转载 作者:行者123 更新时间:2023-11-29 02:11:33 24 4
gpt4 key购买 nike

我遇到了一个奇怪的问题。我有一个 MediaPlayer 的 Activity 应该播放刚录制的音频文件。首先,媒体播放器初始化正常,可以播放文件。

当我旋转屏幕时, Activity 被销毁,然后针对新方向重新初始化。因此,我也重新初始化了媒体播放器。

这工作了几次,但在某些时候 mediaPlayer.setDataSource() 抛出 NullPointerException 因为文件突然消失了。遗憾的是,我没有在日志中看到任何其他错误。

以下是一些代码 fragment :

玩家创建:

/**
* Creates and initializes the player with the proper file.
*/
private void createPlayer() {
synchronized (playerMutex) {
player = new MediaPlayer();
player.setLooping(false);
player.setOnPreparedListener(this);
player.setOnErrorListener(this);
player.setOnCompletionListener(this);
}
readGreeting();
}

播放器初始化:

    isPrepared = false;
try {
final File file = new File(audioFilename);

in = new FileInputStream(file);
synchronized (playerMutex) {
player.setDataSource(in.getFD());
}

// using a runnable instead of prepareAsync to not accidentally call pause on media player while preparing
Runnable preparer = new Runnable() {
@Override
public void run() {
try {
synchronized (playerMutex) {
if (player != null) {
player.prepare();
}
}
} catch (Exception ex) {
Log.e(TAG, "Error preparing player for file " + file.getAbsolutePath(), ex);
}
}
};
new Thread(preparer).start();
} catch (Exception ex) {
btnPlayback.setEnabled(false);
Log.e(TAG, "Error preparing player", ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "initPlayer: ", e);
}
}
}

正在保存实例状态...

@Override
protected void onPause() {
synchronized (playerMutex) {

if (isPlaying()) {
getIntent().putExtra(EXTRA_KEY_SEEK, player.getCurrentPosition());
pause();
}
}
setAudioModeBackToNormal();
super.onPause();
}

private void pause() {
synchronized (playerMutex) {
if (isPlaying()) {
player.pause();
}
}
btnPlayback.setVisibility(View.VISIBLE);
btnPause.setVisibility(View.GONE);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
final Bundle extras = getIntent().getExtras();

outState.putBundle("extras", extras);
super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
getIntent().putExtras(savedInstanceState.getBundle("extras"));
}

清理:

private void stopPlayerAndFreeResources() {
synchronized (playerMutex) {
isPrepared = false;
if (player != null) {
player.stop();
player.release();
player = null;
}
}
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
Log.e(TAG, "Unexpected error", e);
}
}
}

可能是我看问题的角度不对,与播放器无关。有人遇到过文件消失的问题吗?

最佳答案

我让播放列表文件消失了一次。问题的原因原来是某些媒体播放器可以管理我的播放列表。在这种情况下,管理意味着删除我已有的播放列表:(

关于Android:媒体文件从文件系统中消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7031557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com