Skip to content

Instantly share code, notes, and snippets.

@AngelMunoz
Last active June 6, 2020 12:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AngelMunoz/fb5d9d09e252be2e3f750cf3827fcfae to your computer and use it in GitHub Desktop.
Save AngelMunoz/fb5d9d09e252be2e3f750cf3827fcfae to your computer and use it in GitHub Desktop.
uses the new #r "nuget: " directive coming in F# 5.0 plus the C#/WinRT projection to find at most 5 files from your music library and play them 100% natively on Windows 10
#r "nuget: Microsoft.Windows.Sdk.NET, 10.0.18362.3-preview"
open System
open Windows.Media
open Windows.Media.Core
open Windows.Media.Playback
open Windows.Storage
open Windows.Storage.FileProperties
open Windows.Storage.Search
open Windows.Storage.Streams
let asyncGetFiles () =
async {
let queryOpts = QueryOptions()
queryOpts.FileTypeFilter.Add(".mp3")
let query =
KnownFolders.MusicLibrary.CreateFileQueryWithOptions(queryOpts)
let! files = query.GetFilesAsync().AsTask() |> Async.AwaitTask
return files |> Seq.take 5
}
let asyncGetPlaylist =
async {
let! files = asyncGetFiles ()
let playlist = MediaPlaybackList()
for item in files do
let! thumbnail =
item.GetThumbnailAsync(ThumbnailMode.MusicView).AsTask()
|> Async.AwaitTask
let! musicProps =
item.Properties.GetMusicPropertiesAsync().AsTask()
|> Async.AwaitTask
let source = MediaSource.CreateFromStorageFile item
let mediaPlaybackItem = MediaPlaybackItem source
let props = mediaPlaybackItem.GetDisplayProperties()
props.Type <- MediaPlaybackType.Music
props.MusicProperties.Title <- musicProps.Title
props.MusicProperties.AlbumArtist <- musicProps.AlbumArtist
props.MusicProperties.AlbumTitle <- musicProps.Album
props.MusicProperties.Artist <- musicProps.Artist
props.MusicProperties.TrackNumber <- musicProps.TrackNumber
props.Thumbnail <- RandomAccessStreamReference.CreateFromStream thumbnail
mediaPlaybackItem.ApplyDisplayProperties(props)
playlist.Items.Add mediaPlaybackItem
return playlist
}
let player = new MediaPlayer()
async {
let! playlist = asyncGetPlaylist
player.Source <- playlist
player.Play()
}
|> Async.RunSynchronously
let hmsg = "Press q to quit, up arrow to play or pause and arrows to move previous or next"
printfn "%s" hmsg
let mutable key: ConsoleKeyInfo = Console.ReadKey()
let playlist = player.Source :?> MediaPlaybackList
while key.Key <> ConsoleKey.Q do
match key.Key with
| ConsoleKey.RightArrow ->
playlist.MoveNext() |> ignore
| ConsoleKey.LeftArrow ->
playlist.MovePrevious() |> ignore
| ConsoleKey.UpArrow ->
match player.CurrentState with
| MediaPlayerState.Paused -> player.Play()
| MediaPlayerState.Playing -> player.Pause()
| _ -> ()
| ConsoleKey.H -> printfn "\n%s" hmsg
| _ -> ()
key <- Console.ReadKey()
player.Dispose()
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment