问题
I have a single WMA file which contains lots of different pieces of audio. Is there any way I can play part of a sound stream?
Something like:
public static void Play(Stream soundStream, long start, long end);
回答1:
You may be able to do this using NAudio, it is a audio library for .Net.
Using the example here I was able to throw a quick test application up to try it. Using the WaveSteam.Skip(int seconds) method you are able to start at a specific position in the file. I have not been able to work out how to get the end position though. Below is the modified sample that starts a wma file at the 30 second mark:
IWavePlayer waveOutDevice = new WaveOut();
WaveStream mainOutputStream;
WaveChannel32 volumeStream;
WaveStream wmaReader = new WMAFileReader(@"F:\My Music\The Prodigy\Music for the Jilted Generation\01 Intro.wma");
volumeStream = new WaveChannel32(wmaReader);
mainOutputStream = volumeStream;
mainOutputStream.Skip(30); //start 30 seconds into the file
waveOutDevice.Init(mainOutputStream);
waveOutDevice.Play();
The above sample omits the cleanup code to stop playback and dispose of the streams however. Hope that helps a bit.
回答2:
Not in the way you want, no.
I assume this is within a WinForms or WPF context. The solution is to host the WMP ActiveX control in your project, then load the WMA file into it and set the Position/Seek property and then play it for a while and stop it when the Timer reaches a certain point. I don't believe the WMP ActiveX control has a timer event, so you'd need to watch it on another thread and stop the playback when it's reached.
It's a hack, but should work. You should be able to get something that "works" within a few hours if you're familiar with hosting ActiveX controls within .NET applications. Note that you'll want to make your application x86-only because of compatibility issues with the 64-bit WMP ActiveX control.
The, much harder, alternative is to work with DirectShow from within your application and create a Render Graph for WMA files and do the manipulation, seeking and playback yourself. DS has a very steep learning curve, expect this to take you at least a few days to even a few weeks if you've never worked with COM before.
来源:https://stackoverflow.com/questions/13371717/playing-part-of-a-sound-wma-file-in-c-sharp