我正在开发与UWP兼容的Xamarin.Forms应用程序。我的要求是播放,暂停,前进,后退录制的音频文件。为此,我在Xamarin.Forms可移植项目中创建了一个接口
public interface IRecordAudio
{
Task<TimeSpan> SetSource(Stream _stream);
void PlayAudio();
void ForwardAudio();
void RewindAudio();
void PauseAudio();
}
以及UWP项目中接口的实现如下:
public class RecordAudioUWP : IRecordAudio
{
public async Task<TimeSpan> SetSource(Stream _stream)
{
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var folder = await local.GetFolderAsync("Recordings");
var file = await folder.GetFileAsync("MySound.MP3");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
element.SetSource(stream, "");
MusicProperties properties = await
file.Properties.GetMusicPropertiesAsync();
TimeSpan myTrackDuration = properties.Duration;
return myTrackDuration;
}
public void PlayAudio()
{
element.Play();
}
public void ForwardAudio() //Not Working
{
element.Position += TimeSpan.FromSeconds(10);
}
public void PauseAudio()
{
element.Pause();
}
public void RewindAudio() //Not Working
{
element.Position -= TimeSpan.FromMinutes(1);
}
}
正确设置了音频源。音频正确播放和暂停。我在前进和后退音频文件时遇到问题。
请让我知道我做错了什么。感谢
答案 0 :(得分:1)
在Windows 10中,构建1607,我们建议您使用MediaPlayerElement代替MediaElement。 MediaPlayerElement具有与MediaElement相同的功能,同时还支持更高级的媒体播放方案。此外,媒体播放的所有未来改进都将在MediaPlayerElement中进行。
您可以使用MediaPlayerElement
代替MediaElement
,如下所示:
public class RecordAudioUWP : IRecordAudio
{
private MediaPlayerElement element;
private MediaPlayer player;
public async Task<TimeSpan> SetSource(Stream _stream)
{
element = new MediaPlayerElement();
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var folder = await local.GetFolderAsync("Recordings");
var file = await folder.GetFileAsync("MySound.MP3");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
element.Source = MediaSource.CreateFromStream(stream,"");
player = element.MediaPlayer;
MusicProperties properties = await
file.Properties.GetMusicPropertiesAsync();
TimeSpan myTrackDuration = properties.Duration;
return myTrackDuration;
}
public void PlayAudio()
{
player.Play();
}
public void ForwardAudio()
{
var session = player.PlaybackSession;
session.Position += TimeSpan.FromSeconds(10);
}
public void PauseAudio()
{
player.Pause();
}
public void RewindAudio()
{
var session = player.PlaybackSession;
session.Position -= TimeSpan.FromMinutes(1);
}
}