어떻게 확인할 수 있습니 길이(즉시간)니다.wav 파일에서는 C#?

StackOverflow https://stackoverflow.com/questions/82319

  •  01-07-2019
  •  | 
  •  

문제

에 압축하지 않은 상황에 필요를 알고 읽 wav 헤더를 꺼내는 숫자의 채널,비트,그리고 샘플을 평가하고 그것을 밖으로 작동 거기에서:(채널)*(비트)*(견본/s)*(초)=(파일 크기)

더 간단한 방법이 있습 무료 라이브러리,또는에서 뭔가.net framework 아마?

내가 어떻게 이런 경우.wav 파일은 압축(mpeg 코덱에 대한 예)?

도움이 되었습니까?

해결책

사용을 고려할 수 있습제에서는 mcisendstring()함수(오류 확인은 생략):

using System;
using System.Text;
using System.Runtime.InteropServices;

namespace Sound
{
    public static class SoundInfo
    {
        [DllImport("winmm.dll")]
        private static extern uint mciSendString(
            string command,
            StringBuilder returnValue,
            int returnLength,
            IntPtr winHandle);

        public static int GetSoundLength(string fileName)
        {
            StringBuilder lengthBuf = new StringBuilder(32);

            mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
            mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
            mciSendString("close wave", null, 0, IntPtr.Zero);

            int length = 0;
            int.TryParse(lengthBuf.ToString(), out length);

            return length;
        }
    }
}

다른 팁

다운로드 NAudio.dll 에서 링크 http://naudio.codeplex.com/

그 다음 이 기능을 사용하여

public static TimeSpan GetWavFileDuration(string fileName)       
{     
    WaveFileReader wf = new WaveFileReader(fileName);
    return wf.TotalTime; 
}

당신을 얻을 것이기간

하지 않고 멀리 아무것도 대답에서 이미 받아들여지만,나를 얻을 수 있었다 기간의 오디오 파일(여러 가지 서로 다른 포맷을 포함하여,AC3,무엇이 필요한 시간에 사용) Microsoft.DirectX.AudioVideoPlayBack 네임스페이스가 있습니다.이것은 부분의 DirectX9.0 관리되는 코드.대한 참조를 추가하는 내 코드는 다음과 같이 간단합니다...

Public Shared Function GetDuration(ByVal Path As String) As Integer
    If File.Exists(Path) Then
        Return CInt(New Audio(Path, False).Duration)
    Else
        Throw New FileNotFoundException("Audio File Not Found: " & Path)
    End If
End Function

그리고 그것은 매우 빠르다!여기에 참조 오디오 클래스입니다.

나는 어려움으로 예 MediaPlayer-위의 클래스.어느 정도 시간이 소요될 수 있습니다 전에,플레이어는 파일을 열.서"현실 세계"당신은 등록을 위한 MediaOpened 이벤트,후에는 해고의 NaturalDuration 유효합니다.콘솔에서-응용 프로그램 당신은 단지 몇 초 후에 열려 있습니다.

using System;
using System.Text;
using System.Windows.Media;
using System.Windows;

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      if (args.Length == 0)
        return;
      Console.Write(args[0] + ": ");
      MediaPlayer player = new MediaPlayer();
      Uri path = new Uri(args[0]);
      player.Open(path);
      TimeSpan maxWaitTime = TimeSpan.FromSeconds(10);
      DateTime end = DateTime.Now + maxWaitTime;
      while (DateTime.Now < end)
      {
        System.Threading.Thread.Sleep(100);
        Duration duration = player.NaturalDuration;
        if (duration.HasTimeSpan)
        {
          Console.WriteLine(duration.TimeSpan.ToString());
          break;
        }
      }
      player.Close();
    }
  }
}

Try 코드는 아래에서 는 방법을의 길이를 결정합니다.wav 파일에서는 C#

    string path = @"c:\test.wav";
    WaveReader wr = new WaveReader(File.OpenRead(path));
    int durationInMS = wr.GetDurationInMS();
    wr.Close();

Yes,무료 라이브러리를 사용할 수 있는 시간을 얻을 시간의 오디오 파일입니다.이 라이브러리는 또한 제공합니다 더 많은 기능입니다.

에서 사용하기 위한 것

에서 사용하기 위한 것입 distributed under GNU Lesser General Public License(LGPL)Mozilla Public License(MPL).

구현 아래 코드를 반환하는 기간에서는 초입니다.

using TagLib.Mpeg;

public static double GetSoundLength(string FilePath)
{
    AudioFile ObjAF = new AudioFile(FilePath);
    return ObjAF.Properties.Duration.TotalSeconds;
}

을 찾을 수 있습는 XNA 라이브러리 는 몇 가지 작업을 지원하 WAV 의 등입니다.하고자하는 경우 아래로 이동하는 경로입니다.그것은 작동하도록 설계되었 C#한 게임 프로그래밍 수도 있습니다 그래서 그냥 돌게 당신이 필요합니다.

가의 튜토리얼(로-아마도 작동 코드를 활용할 수 있습니다)에서 이상 CodeProject.

만 당신은 약간의 그것의 완벽하게"정상"에 대해 WAV 파일을 구성하는 여러 개의 덩어-그래서 당신을 조금씩 전체 파일을 보장하는 모든 덩어리를 차지합니다.

정확히 무엇입 응용 프로그램을 압축 WAVs?압축 WAV 파일은 항상 어려운 난 항상 노력하고 대안을 사용 컨테이너 형식 이 경우에는 같은 OGG 또는 WMA files.XNA 라이브러리는 경향이 작동하도록 설계되었으로 특정한 형식이는 것이 가능하지만 내 XACT 당신이 찾을 보다 일반적인 wav 재생 방법입니다.가능한 대안으로 보는 것입니다 SDL C#포트,하지만 나는 지금까지 사용을 압축하지 않은 WAVs-열면 쿼리할 수 있습 샘플의 수를 결정하는 길이 있습니다.

난 말 MediaInfo, 에,나는 그것을 사용하고있 년 이상으로 오디오/비디오 인코딩 응용 프로그램에서 일하고 있어요.제공하는 모든 정보를 위해 wav 파일와 함께 거의 모든 다른 형식입니다.

MediaInfoDll 샘플 C#코드에서 어떻게 얻습니다.

내가 상황을 가정하여 설명하고 있습니다 다소 익숙한 구조다.WAV 파일:그것은 포함 WAVEFORMATEX 헤더의 구조체의 수에 따라 다른 구조(또는 덩어리)포함한 다양한 종류의 정보입니다.보 Wikipedia 에 대한 더 많은 정보에 파일 형식입니다.

첫째,을 반복합니다.wav 파일을 추가합 덧붙여지지 않은 길이의 데이터""덩어리(the"data"덩어리를 포함 오디오 데이터에 대한 파일일반적으로만 이들 중 하나,하지만 그것은 가능한 될 수 있는 하나 이상).지금 당신은 전체 크기를 바이트 단위의 오디오 데이터입니다.

다음 얻을 수"평균 바이트로 초당"회원 WAVEFORMATEX 헤더의 구조체의 파일입니다.

마지막으로 나눈 총 크기의 오디오 데이터에 의하여 평균 바이트로 초당-이 기간 동안 파일에서는 초입니다.

이에 대해 합리적으로 잘 작동 압축되지 않고 압축 파일이 있습니다.

시간=FileLength/(샘플을 평가*채널*샘플당 비트/8)

내가 테스트 불어 코드 실패,파일 형식은 다음과 같"\\ip\dir\*.wav'

 public static class SoundInfo
   {
     [DllImport("winmm.dll")]
     private static extern uint mciSendString
     (
        string command,
        StringBuilder returnValue,
        int returnLength,
        IntPtr winHandle
     );

     public static int GetSoundLength(string fileName)
      {
        StringBuilder lengthBuf = new StringBuilder(32);

        mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
        mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
        mciSendString("close wave", null, 0, IntPtr.Zero);

        int length = 0;
        int.TryParse(lengthBuf.ToString(), out length);

        return length;
    }
}

동 naudio works

    public static int GetSoundLength(string fileName)
     {
        using (WaveFileReader wf = new WaveFileReader(fileName))
        {
            return (int)wf.TotalTime.TotalMilliseconds;
        }
     }`
Imports System.IO
Imports System.Text

Imports System.Math
Imports System.BitConverter

Public Class PulseCodeModulation
    ' Pulse Code Modulation WAV (RIFF) file layout

    ' Header chunk

    ' Type   Byte Offset  Description
    ' Dword       0       Always ASCII "RIFF"
    ' Dword       4       Number of bytes in the file after this value (= File Size - 8)
    ' Dword       8       Always ASCII "WAVE"

    ' Format Chunk

    ' Type   Byte Offset  Description
    ' Dword       12      Always ASCII "fmt "
    ' Dword       16      Number of bytes in this chunk after this value
    ' Word        20      Data format PCM = 1 (i.e. Linear quantization)
    ' Word        22      Channels Mono = 1, Stereo = 2
    ' Dword       24      Sample Rate per second e.g. 8000, 44100
    ' Dword       28      Byte Rate per second (= Sample Rate * Channels * (Bits Per Sample / 8))
    ' Word        32      Block Align (= Channels * (Bits Per Sample / 8))
    ' Word        34      Bits Per Sample e.g. 8, 16

    ' Data Chunk

    ' Type   Byte Offset  Description
    ' Dword       36      Always ASCII "data"
    ' Dword       40      The number of bytes of sound data (Samples * Channels * (Bits Per Sample / 8))
    ' Buffer      44      The sound data

    Dim HeaderData(43) As Byte

    Private AudioFileReference As String

    Public Sub New(ByVal AudioFileReference As String)
        Try
            Me.HeaderData = Read(AudioFileReference, 0, Me.HeaderData.Length)
        Catch Exception As Exception
            Throw
        End Try

        'Validate file format

        Dim Encoder As New UTF8Encoding()

        If "RIFF" <> Encoder.GetString(BlockCopy(Me.HeaderData, 0, 4)) Or _
            "WAVE" <> Encoder.GetString(BlockCopy(Me.HeaderData, 8, 4)) Or _
            "fmt " <> Encoder.GetString(BlockCopy(Me.HeaderData, 12, 4)) Or _
            "data" <> Encoder.GetString(BlockCopy(Me.HeaderData, 36, 4)) Or _
            16 <> ToUInt32(BlockCopy(Me.HeaderData, 16, 4), 0) Or _
            1 <> ToUInt16(BlockCopy(Me.HeaderData, 20, 2), 0) _
        Then
            Throw New InvalidDataException("Invalid PCM WAV file")
        End If

        Me.AudioFileReference = AudioFileReference
    End Sub

    ReadOnly Property Channels() As Integer
        Get
            Return ToUInt16(BlockCopy(Me.HeaderData, 22, 2), 0) 'mono = 1, stereo = 2
        End Get
    End Property

    ReadOnly Property SampleRate() As Integer
        Get
            Return ToUInt32(BlockCopy(Me.HeaderData, 24, 4), 0) 'per second
        End Get
    End Property

    ReadOnly Property ByteRate() As Integer
        Get
            Return ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0) 'sample rate * channels * (bits per channel / 8)
        End Get
    End Property

    ReadOnly Property BlockAlign() As Integer
        Get
            Return ToUInt16(BlockCopy(Me.HeaderData, 32, 2), 0) 'channels * (bits per sample / 8)
        End Get
    End Property

    ReadOnly Property BitsPerSample() As Integer
        Get
            Return ToUInt16(BlockCopy(Me.HeaderData, 34, 2), 0)
        End Get
    End Property

    ReadOnly Property Duration() As Integer
        Get
            Dim Size As Double = ToUInt32(BlockCopy(Me.HeaderData, 40, 4), 0)
            Dim ByteRate As Double = ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0)
            Return Ceiling(Size / ByteRate)
        End Get
    End Property

    Public Sub Play()
        Try
            My.Computer.Audio.Play(Me.AudioFileReference, AudioPlayMode.Background)
        Catch Exception As Exception
            Throw
        End Try
    End Sub

    Public Sub Play(playMode As AudioPlayMode)
        Try
            My.Computer.Audio.Play(Me.AudioFileReference, playMode)
        Catch Exception As Exception
            Throw
        End Try
    End Sub

    Private Function Read(AudioFileReference As String, ByVal Offset As Long, ByVal Bytes As Long) As Byte()
        Dim inputFile As System.IO.FileStream

        Try
            inputFile = IO.File.Open(AudioFileReference, IO.FileMode.Open)
        Catch Exception As FileNotFoundException
            Throw New FileNotFoundException("PCM WAV file not found")
        Catch Exception As Exception
            Throw
        End Try

        Dim BytesRead As Long
        Dim Buffer(Bytes - 1) As Byte

        Try
            BytesRead = inputFile.Read(Buffer, Offset, Bytes)
        Catch Exception As Exception
            Throw
        Finally
            Try
                inputFile.Close()
            Catch Exception As Exception
                'Eat the second exception so as to not mask the previous exception
            End Try
        End Try

        If BytesRead < Bytes Then
            Throw New InvalidDataException("PCM WAV file read failed")
        End If

        Return Buffer
    End Function

    Private Function BlockCopy(ByRef Source As Byte(), ByVal Offset As Long, ByVal Bytes As Long) As Byte()
        Dim Destination(Bytes - 1) As Byte

        Try
            Buffer.BlockCopy(Source, Offset, Destination, 0, Bytes)
        Catch Exception As Exception
            Throw
        End Try

        Return Destination
    End Function
End Class

"다운로드 PresentationCore.dll"및"WindowsBase.dll 에서":

http://www.search-dll.com/dll-files/download/windowsbase.dll.html

를 붙여 파일에서 당신은 응용 프로그램 bin 폴더에 참조용입니다.이제 작동합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top