简体   繁体   中英

NAudio from stream? play audio

I am trying to convert my .net project to .net core (IoT core). Everything is working except my "system.media" block as .net core doesn't come with system.media at all. My options to this is to use NAudio apparently. However, I have no clue how to make NAudio play audio from a Stream.

This is the current code I am trying to convert with NAudio. Any suggestions?

public void PlayAudio(object sender, GenericEventArgs<Stream> args)
{
SoundPlayer player = new SoundPlayer(args.EventData);
player.PlaySync();
args.EventData.Dispose();
}

I tried with this code but got no success.

        using (Stream ms = new MemoryStream())
    {
        using (Stream stream = WebRequest.Create(url)
            .GetResponse().GetResponseStream())
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
        }

        ms.Position = 0;
        using (WaveStream blockAlignedStream =
            new BlockAlignReductionStream(
                WaveFormatConversionStream.CreatePcmStream(
                    new Mp3FileReader(ms))))
        {
            using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
            {
                waveOut.Init(blockAlignedStream);
                waveOut.Play();                        
                while (waveOut.PlaybackState == PlaybackState.Playing )                        
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
        }
    }

Have you tried using the AudioGraph APIs ? These are a great way to play audio on IoT Core. I've used it with success on a Raspberry Pi.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM