c# - 如何阻止 MediaPlayer 每次启动?
问题描述
我将如何修复接收字节的 MediaPlayer 代码,而不是创建一个临时文件,即保存输入,但对于每个输入,播放器从头开始,我希望它只是播放。这是我的代码:
Java.IO.File temp = Java.IO.File.CreateTempFile("temp", "mp3");
Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(temp);
Java.IO.FileInputStream fis = new Java.IO.FileInputStream(temp);
temp.DeleteOnExit();
MediaPlayer player = new MediaPlayer();
player.SetDataSource(fis.FD);
// If set here, there is an error
//12-09 17:29:44.472 V/MediaPlayer( 9927): setDataSource(58, 0, 576460752303423487)
//12-09 17:29:44.472 E/MediaPlayer( 9927): Unable to to create media player
while (true)
{
try
{
byte[] myReadBuffer = new byte[10000]; //Input array
mmInStream.Read(myReadBuffer, 0, myReadBuffer.Length); //Reads the incoming array into myReadBuffer
fos.Write(myReadBuffer, 0, myReadBuffer.Length); //Writes it into temp file
MediaPlayer player = new MediaPlayer(); //Creates a new object
player.SetDataSource(fis.FD); // If here, it would just start from the start each time and add more // Sets the data source to temp file
player.Prepare();
player.Start();
while (true)
{
// Checks if it can release resources
if (!player.IsPlaying)
{
player.Release();
break;
}
}
}
catch (System.IO.IOException ex)
{
System.Diagnostics.Debug.WriteLine("Input stream was disconnected", ex);
}
}
我正在使用 Xamari 表单。
基本上,我得到一个字节数组,存储在一个临时文件中,然后尝试播放它们。我知道每个循环都会重新创建 MediaPlayer,因为我在那里定义了数据源,但是如果我把它放在循环之外,它会得到一个错误(如上所述)。
示例:歌曲开始播放大约 2 秒,然后重新开始,但现在播放 4 秒,然后再次播放,现在播放 6 秒。每一次,更多的歌曲被揭示出来。
如果它是一个字符串,它会是这样的:
123
123456
123456789
我怎样才能让它连续播放,但每次它只会播放一个新的部分?
解决方案
这是一个逻辑问题。本质上,您是将块写入流,然后播放该块,然后在不重置流的情况下写入更多内容,然后从该流的开头播放。
您需要它做的是将一个块写入您的流,播放该流,然后将一个新块写入流并播放该流。
- 将您的
Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(temp);
内部移动到外部while()
循环中。
这样做的原因是您正在写入您fos
当时正在播放的内容,然后再次写入但不处理您的初始缓冲区数据。进入您的 while 循环会强制创建一个新对象,该对象将fos
包含新的缓冲区数据,然后它将播放该对象。由于循环和必须重新加载要播放的新数据,音频跳过会出现问题。
要更正跳过,您需要在播放缓冲区时异步加载它。您可以使用单独的线程来执行此操作。您可能需要调整缓冲区大小或设置缓冲区条件。MediaPlayer
包含一个BufferingProgress
可能有帮助的属性。
推荐阅读
- c - C 中的评分点
- java - Str中的char的递归计数-Java
- doxygen - 获取 doxygen 以处理来自 #include 指令的文件
- sql-server - 在 SSRS 2008 中,如何将变量从一份报告传递到另一份报告?
- elasticsearch - ElasticSearch Canvas - 下拉菜单不起作用
- stm32 - STM32 SWD协议-端口号
- android - Sqlite 表用户函数
- php - 单击提交按钮时数据未更新
- docker - docker push to Google Container Registry 错误“调用者没有权限‘storage.buckets.create’”
- java - 如何从 react-native 本机模块访问子级?