문제

In my C# project I want to play a sound with a specified start- and end time.

I used the System.Media.SoundPlayer with the .Play() function. But with this function I can only play the whole sound file or can abort it after I have counted the runtime.

In fact I want to say, that the given sound file should start for example at time 1m:25s:30ms and should end at time 1m:50s:00ms or after a duration of 10s or so.

Does anybody know a simple solution for his problem?

Thanks 4 help.

도움이 되었습니까?

해결책 3

In the End I use the NAudio library. That can handle this - not in a perfect way but ok. see https://stackoverflow.com/a/13372540/2936206

다른 팁

Not really an answer, but this question got me wondering if you can do something like this:

long startPositionInBytes = 512;
long endPositionInBytes = 2048;

using ( var audioStream = File.OpenRead(@"audio.wav") )
{
    audioStream.Position = startPositionInBytes;

    using ( var player = new SoundPlayer(audioStream) )
    {
        player.Play();

        do
        {
            Thread.Sleep(1);
        } while ( audioStream.Position <= endPositionInBytes );

        player.Stop();
    }
}

In case you want to play a Background Media Player (for e.g., an audio file) which would start from a specific time and would work for a certain duration, then this code snippet could also be useful:

StorageFile mediaFile = await KnownFolders.VideosLibrary.GetFileAsync(fileName);//the path
BackgroundMediaPlayer.Current.SetFileSource(mediaFile);
BackgroundMediaPlayer.Current.Position = TimeSpan.FromMilliseconds(3000/*enter the start time here*/);
BackgroundMediaPlayer.Current.Play();
await Task.Delay(TimeSpan.FromMilliseconds(10000/*for how long you want to play*/));
BackgroundMediaPlayer.Shutdown();//stops the player

**But this would only work for Windows 8.1 and above. For more information, click here...

I got it to work by using Windows Media Player in a C sharp program with a timer control and an open dialog. I followed a sample that used buttons on the form and made the media player invisible. After opening the file with an Open button that used the open dialog to open the mp3 file, on the Play button I put this code [the end effect is that it started the file in position 28.00 and ended it in position 32.50]:

private void button2_Click(object sender, EventArgs e)
{
    axWindowsMediaPlayer1.URL = openFileDialog1.FileName;
    timer1.Start();
    axWindowsMediaPlayer1.Ctlcontrols.currentPosition = 28.00;
    axWindowsMediaPlayer1.Ctlcontrols.play();    
}

Then in the timer tick event:

private void timer1_Tick(object sender, EventArgs e)
{
    if (axWindowsMediaPlayer1.Ctlcontrols.currentPosition >= 32.50)
    { axWindowsMediaPlayer1.Ctlcontrols.pause(); }
        label1.Text = String.Format("{0:0.00}", 
    axWindowsMediaPlayer1.Ctlcontrols.currentPosition);     
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top