如何停止每次启动MediaPlayer?

问题描述 投票:1回答:1

我将如何修复接收字节的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 incomming 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

我将如何使其连续播放,但每次只能播放新的部分?

c# audio android-mediaplayer
1个回答
1
投票

这是一个逻辑问题。本质上,您是在向流中写入块,然后播放该块,然后在不重置流的情况下编写更多内容,然后从该流的开头开始播放。

您需要做的是向流中写入一个块,播放该流,然后向该流中写入一个新的块并播放该流。

  • Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(temp);移动到外部while()循环中。

起作用的原因是,您正在写入fos,然后播放,然后再次写入,但不丢弃初始缓冲区数据。将fos移入while循环会强制创建一个新对象,其中将包含新的缓冲区数据,然后它将播放它。由于循环和必须重新加载要播放的新数据,音频跳过会出现问题。

要更正跳过,您需要在播放缓冲区时异步加载它。您可以使用单独的线程执行此操作。您可能需要调整缓冲区大小或设置缓冲区条件。 MediaPlayer包含可能有用的BufferingProgress属性。

© www.soinside.com 2019 - 2024. All rights reserved.