简体   繁体   中英

Play .wma from memory stream using NAudio

I'm working on a C# app in Visual Studio 2013 that needs to play audio files in .wav, .mp3 and .wma formats. the .wav and mp3 files play with no problem. .wma files, however, seem to require extra handling and I'm at a loss to find a solution.

Here are the using statements at the top of the project file:

using NAudio;
using NAudio.Wave;
using NAudio.FileFormats.Wav;
using NAudio.FileFormats.Mp3;
using NAudio.WindowsMediaFormat;
using NAudio.MediaFoundation;

And here's the code for playback:

    private void PlayIntroScreenAudio()
    {
        Player.Stop();
        byte[] IntroAudioInBytes = Convert.FromBase64String(GameInfo.IntroScreenAudio);
        MemoryStream msIntroAudioStream = new MemoryStream(IntroAudioInBytes, 0, IntroAudioInBytes.Length);
        msIntroAudioStream.Write(IntroAudioInBytes, 0, IntroAudioInBytes.Length);
        msIntroAudioStream.Seek(0, SeekOrigin.Begin);
        msIntroAudioStream.Position = 0;

        if (GameInfo.IntroScreenAudioFileExt == ".wav")
        {
            WaveFileReader wfr = new WaveFileReader(msIntroAudioStream);
            Player.Init(wfr);
        }
        else if (GameInfo.IntroScreenAudioFileExt == ".mp3")
        {
            Mp3FileReader mp3rdr = new Mp3FileReader(msIntroAudioStream);
            Player.Init(mp3rdr);
        }
        else if (GameInfo.IntroScreenAudioFileExt == ".wma")
        {
            WMAFileReader wmafr = new WMAFileReader(msIntroAudioStream);
            Player.Init(wmafr);
        }
        Player.Play();
        IntroAudioIsPlaying = true;
        FinalScoreAudioIsPlaying = QuestionAudioIsPlaying = CARAudioIsPlaying = IARAudioIsPlaying = false;
        btnPlayIntroScreenAudio.Image = Properties.Resources.btnStopIcon;
        btnPlayFinalScoreAudio.Image = btnPlayQuestionAudio.Image = btnPlayCorrectResponseAudio.Image =
            btnPlayIncorrectResponseAudio.Image = Properties.Resources.btnPlayIcon;
        Player.PlaybackStopped += Player_PlaybackStopped;
    }

As you'll probably guess, I get a wiggly line under "(msIntroAudioStream)". I tried adding ".ToString() inside the parentheses, but VS says it's wrong, since wmafr can't read from a string. What other code do I need to play a .wma file?

WMAFileReader only supports input from a file and it expects a string representing a path to file in its constructor's argument.

If you want to use WMAFileReader , you would have to write your MemoryStream to a file first, and then feed the path to WMAFileReader .

Curiously enough, WMAFileReader has no constructor taking a Stream as an argument, but Mp3FileReader and WaveFileReader both do.

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