Beispiel #1
1
 public XAudioMusic(string filename, XAudioDevice device)
     : base(filename, device)
 {
     musicStream = new Mp3Stream(File.OpenRead("Content/" + filename + ".mp3"));
     source = new SourceVoice(device.XAudio2,
         new WaveFormat(musicStream.Samplerate, 16, musicStream.Channels), false);
     CreateBuffers();
 }
Beispiel #2
0
 /// <summary>
 /// Uses ID3.NET.
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="stream"></param>
 /// <returns></returns>
 public static SongInfo ReadId3(string filePath, Stream stream)
 {
     try {
         using (var mp3 = new Mp3Stream(stream)) {
             var tags = new List <Id3Tag>(mp3.GetAllTags());
             if (tags.Count > 0)
             {
                 var firstTag = tags.First();
                 var title    = firstTag.Title.Value;
                 if (String.IsNullOrWhiteSpace(title))
                 {
                     title = PathHelper.Instance.FileNameWithoutExtension(filePath);
                 }
                 // All ID3 libraries for WP suck; no way to get duration reliably prior to opening in a player,
                 // so sets duration to 0 for now and obtain it when needed for playback.
                 return(new SongInfo(title, firstTag.Artists.Value, firstTag.Album.Value, TimeSpan.FromSeconds(0)));
             }
             else
             {
                 return(null);
             }
         }
     } catch (IndexOutOfRangeException) {
         // maybe thrown if the file is cocked up and id3 tags cannot be read
         return(null);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Disposes this WaveStream
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                while (this.TableCreater.IsAlive)
                {
                    this.tableCreated = true;
                    Thread.Sleep(1);
                }

                if (Mp3Stream != null)
                {
                    if (ownInputStream)
                    {
                        Mp3Stream.Dispose();
                    }
                    Mp3Stream = null;
                }
                if (decompressor != null)
                {
                    decompressor.Dispose();
                    decompressor = null;
                }
            }
            base.Dispose(disposing);
        }
Beispiel #4
0
        private void WithID3_Net()
        {
            string[] musicFiles = Directory.GetFiles(txtFolderPath.Text, "*.mp3");
            foreach (string musicFile in musicFiles)
            {
                using (var mp3 = new Mp3File(musicFile, Mp3Permissions.ReadWrite))
                {
                    Console.WriteLine(musicFile);
                    Console.WriteLine(mp3.HasTagOfFamily(Id3TagFamily.FileStartTag).ToString());
                    var x   = this.GetValidVersion(mp3);
                    var tag = mp3.GetTag(x.Major, x.Minor);
                    Console.WriteLine("Title: {0}", tag.Title.Value);
                    Console.WriteLine("Artist: {0}", tag.Artists.Value);
                    Console.WriteLine("Album: {0}", tag.Album.Value);
                    Mp3Stream xs = new Mp3Stream(new MemoryStream());

                    mp3.WriteTag(tag, x.Major, x.Minor, WriteConflictAction.Replace);

                    foreach (var item in tag.Frames)
                    {
                        Console.WriteLine(item.ToString());
                    }
                    //Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                    //Console.WriteLine("Title: {0}", tag.Title.Value);
                    //Console.WriteLine("Artist: {0}", tag.Artists.Value);
                    //Console.WriteLine("Album: {0}", tag.Album.Value);
                }
            }
        }
Beispiel #5
0
 private void testId3(string filePath)
 {
     if (!File.Exists(filePath))
     {
         Debug.WriteLine(filePath + " does not exist");
         return;
     }
     else
     {
         Debug.WriteLine(filePath + " exists");
     }
     using (var file = new FileStream(filePath, FileMode.Open)) {
         using (var mp3 = new Mp3Stream(file)) {
             //var t = mp3.GetTag(Id3TagFamily.Version2x);
             //Debug.WriteLine(t.Title.Value);
             var tags     = new List <Id3Tag>(mp3.GetAllTags());
             var tagCount = tags.Count;
             tags.ForEach(tag => {
                 Debug.WriteLine(tag.Title.Value);
             });
             Debug.WriteLine("tags: " + tagCount);
             Debug.WriteLine("duration: " + mp3.Audio.Duration.TotalSeconds);
             Debug.WriteLine("bitrate: " + mp3.Audio.Bitrate);
             Assert.AreEqual(506, mp3.Audio.Duration);
         }
     };
 }
Beispiel #6
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Mp3Stream mp3Stream = new Mp3Stream(AppDomain.CurrentDomain.BaseDirectory + @"/Sample/sample2.mp3");

            WaveFile waveFile       = new WaveFile();
            int      openfileResult = waveFile.OpenFile(AppDomain.CurrentDomain.BaseDirectory + @"/Sample/sample2.wav", WaveFormat.WF_PCM_S16LE, false, 8000, 1);

            if (openfileResult == 0)
            {
                short[,] data = null;
                byte[] buffer = new byte[512];
                int    ret;

                ret = mp3Stream.Read(buffer, 0, buffer.Length);
                Console.WriteLine("File Format: {0}", mp3Stream.Format);
                Console.WriteLine("Frequency: {0}", mp3Stream.Frequency);
                Console.WriteLine("Channel Count: {0}", mp3Stream.ChannelCount);

                if (mp3Stream.ChannelCount <= 0 || mp3Stream.Frequency <= 0)
                {
                    Console.WriteLine("Cannnot decode file.");
                }
                else
                {
                    waveFile.CreateData(ref data, 128);
                    Console.WriteLine("Data Length [{0},{1}]", data.GetLength(0), data.GetLength(1));

                    while (ret != 0)
                    {
                        int i;
                        for (i = 0; i < data.GetLength(1); i++)
                        {
                            if (i * 4 >= ret)
                            {
                                break;
                            }
                            double p1 = (double)BitConverter.ToInt16(buffer, i * 2) / 32767.0;
                            data[0, i] = (short)(
                                ((double)BitConverter.ToInt16(buffer, i * 4) / 32767.0
                                 + (double)BitConverter.ToInt16(buffer, i * 4 + 2) / 32767.0
                                ) * 32767.0 / 2.0);
                        }
                        waveFile.PutData(data, i);
                        ret = mp3Stream.Read(buffer, 0, buffer.Length);
                    }
                }
                waveFile.FlushFile();
                waveFile.CloseFile();
            }
            else
            {
                Console.WriteLine("Can not create waveFile:{0}", openfileResult);
            }

            Console.WriteLine("Finished");
            Console.ReadLine();
            return;
        }
Beispiel #7
0
 private static void PlayMP3SoundData(ref List <PCMSample> audioStream)
 {
     using var finalFile   = new Mp3Stream(audioStream);
     using var m           = new System.IO.MemoryStream(finalFile.GetRawWaveStream());
     using var soundPlayer = new System.Media.SoundPlayer(m);
     soundPlayer.PlaySync();
 }
Beispiel #8
0
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    var options  = OptionsFromArgs();
                    var recorder = new Recorder(
                        options
                        );

                    var mp3stream = new Mp3Stream(
                        options.Url
                        );

                    recorder.ProcessFrames(
                        mp3stream.GetFrames()
                        );
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.WriteLine("Restarting...");
                }
            }
        }
        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            string startFolder = @"C:\Users\ppras_000\Desktop\Creating Lasting Change";

            DirectoryInfo di = new DirectoryInfo(startFolder);

            foreach (var dir in di.GetDirectories())
            {
                foreach (var file in dir.GetFiles("*.mp3"))
                {
                    using (FileStream fs = new FileStream(file.FullName, FileMode.Open))
                    {
                        using (var mp3 = new Mp3Stream(fs, Mp3Permissions.ReadWrite))
                        {
                            Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2x);
                            tag.Title.Value = file.Name.Substring(0, 2);
                            tag.Album.Value = dir.Name.Substring(0, 6);
                            mp3.WriteTag(tag);
                        }
                    }
                }
            }



            MessageBox.Show("Done");
        }
Beispiel #10
0
        public void Write(Mp3MetaData mp3MetaData, string inputFilePath)
        {
            using (var fileStream = new FileStream(inputFilePath, FileMode.Open))
            {
                using (var mp3 = new Mp3Stream(fileStream, Mp3Permissions.ReadWrite))
                {
                    mp3.DeleteAllTags(); // make sure the file got no tags

                    var id3Tag = new Id3Tag();
                    id3Tag.Title.Value = mp3MetaData.Title;
                    foreach (var artist in mp3MetaData.Artists)
                    {
                        id3Tag.Artists.Value.Add(artist);
                    }
                    id3Tag.Album.Value = mp3MetaData.Album;
                    id3Tag.Year.Value  = mp3MetaData.Year;
                    id3Tag.Pictures.Add(new PictureFrame()
                    {
                        PictureType = PictureType.FrontCover, PictureData = mp3MetaData.Cover
                    });

                    mp3.WriteTag(id3Tag, 2, 3);
                }
            }
        }
 public int sceMp3NotifyAddStreamData(Mp3Stream Mp3Stream, int Size)
 {
     Mp3Stream.AddStreamData(
         PointerUtils.PointerToByteArray(
             (byte *)Mp3Stream.Mp3Arguments->Mp3BufferPointer.GetPointer(Memory, Size), Size)
         );
     return(0);
 }
Beispiel #12
0
        public static void Read(string path, Sound sound)
        {
            if (!File.Exists(path))
                return;

            File.SetAttributes(path, FileAttributes.Normal);

            try
            {
                Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                Mp3Stream mp3 = new Mp3Stream(stream);

                if (!mp3.HasTags)
                {
                    stream.Close();
                    ComputeFromFileName(path, sound);
                    return;
                }

                //mp3.GetAudioStream().
                var tags = mp3.GetAllTags();

                foreach (var tag in tags)
                    if (tag != null)
                    {
                        if (string.IsNullOrWhiteSpace(tag.Artists.Value) && string.IsNullOrWhiteSpace(tag.Title.Value))
                        {
                            ComputeFromFileName(path, sound);
                        }
                        else
                        {
                          byte[] input = null;

                          if (!string.IsNullOrWhiteSpace(tag.Title.Value))
                          {
                              input = tag.Title.Encode();
                              sound.title = ConvertEncoding(tag.Artists.Value, input, Id3TextEncoding.Iso8859_1);
                          }

                          if (!string.IsNullOrWhiteSpace(tag.Artists))
                          {
                              input = tag.Artists.Encode();
                              sound.artist = ConvertEncoding(tag.Artists.Value, input, Id3TextEncoding.Iso8859_1);
                          }
                        }

                        GetPicture(tag);
                        //int.TryParse(tag.BeatsPerMinute.Value, out modelView.duration);
                        break;
                    }
                stream.Close();

            }//try
            catch (Exception)
            {
                ComputeFromFileName(path, sound);
            }
        }
Beispiel #13
0
 public OpenTKMusic(string filename, SoundDevice device)
     : base(filename, device)
 {
     musicStream = new Mp3Stream(File.OpenRead("Content/" + filename + ".mp3"));
     format = musicStream.Channels == 2 ? ALFormat.Stereo16 : ALFormat.Mono16;
     source = AL.GenSource();
     buffers = AL.GenBuffers(NumberOfBuffers);
     bufferData = new byte[BufferSize];
 }
Beispiel #14
0
        public override void Dispose()
        {
            if (musicStream == null)
                return;

            Stop();
            musicStream = null;

            if (source != null)
                DisposeSource();
        }
Beispiel #15
0
        /// <summary>
        /// http://id3.codeplex.com/
        /// </summary>
        /// <param name="track"></param>
        public void getMP3Data(Track track)
        {
            var fs  = new FileStream(MediaFilename, FileMode.Open, FileAccess.Read);
            var mp3 = new Mp3Stream(fs);

            Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);

            track.title  = tag.Title.Value;
            track.artist = tag.Artists.Value;

            fs.Close();
        }
Beispiel #16
0
        private Thread MainThread; //keep track of this, terminate when it closes.

        public MP3Player(string path)
        {
            Stream = new Mp3Stream(path);
            Stream.DecodeFrames(1); //let's get started...

            DecodeNext = new AutoResetEvent(true);
            BufferDone = new AutoResetEvent(false);

            Inst               = new DynamicSoundEffectInstance(Stream.Frequency, AudioChannels.Stereo);
            Inst.IsLooped      = false;
            Inst.BufferNeeded += SubmitBufferAsync;
            SubmitBuffer(null, null);
            SubmitBuffer(null, null);

            NextBuffers   = new List <byte[]>();
            NextSizes     = new List <int>();
            Requests      = 1;
            MainThread    = Thread.CurrentThread;
            DecoderThread = new Thread(() =>
            {
                try
                {
                    while (MainThread.IsAlive)
                    {
                        DecodeNext.WaitOne(128);
                        bool go;
                        lock (this) go = Requests > 0;
                        while (go)
                        {
                            var buf  = new byte[524288];
                            var read = Stream.Read(buf, 0, buf.Length);
                            lock (this)
                            {
                                Requests--;
                                NextBuffers.Add(buf);
                                NextSizes.Add(read);
                                if (read == 0)
                                {
                                    EndOfStream = true;
                                    return;
                                }
                                BufferDone.Set();
                            }
                            lock (this) go = Requests > 0;
                        }
                    }
                }
                catch (Exception e) { }
            });
            DecoderThread.Start();
        }
Beispiel #17
0
        private string GetGenre(HttpPostedFileBase file)
        {
            var genre = string.Empty;
            using (var mp3 = new Mp3Stream(file.InputStream))
            {
                Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                genre = tag.Genre;
                Console.WriteLine("Title: {0}", tag.Title.Value);
                Console.WriteLine("Artist: {0}", tag.Artists.Value);
                Console.WriteLine("Album: {0}", tag.Album.Value);

            }

            return genre;
        }
        public static TrackInfo GetTrackInfo(string mp3Path)
        {
            var trackInfo = new TrackInfo();

            using (var currentStream = new Mp3Stream(new FileStream(mp3Path, Open, Read)))
            {
                var id3Tag = currentStream.GetTag(Id3TagFamily.FileStartTag);
                trackInfo.Atrist    = id3Tag.Artists?.Value;
                trackInfo.Title     = id3Tag.Title?.Value;
                trackInfo.Bitrate   = currentStream.Audio.Bitrate;
                trackInfo.Duration  = currentStream.Audio.Duration;
                trackInfo.Frequency = currentStream.Audio.Frequency;
            }

            return(trackInfo);
        }
Beispiel #19
0
 /// <summary>
 /// Callback for the loopback recorder, new audio data is captured.
 /// </summary>
 /// <param name="dataToSendIn">the audio data in wav format</param>
 /// <param name="formatIn">the wav format that's used</param>
 public void OnRecordingDataAvailable(byte[] dataToSendIn, WaveFormat formatIn)
 {
     if (!StreamFormatSelected.Equals(SupportedStreamFormat.Wav))
     {
         if (Mp3Stream == null)
         {
             Mp3Stream = new Mp3Stream(formatIn, StreamFormatSelected);
         }
         Mp3Stream.Encode(dataToSendIn.ToArray());
         dataToSendIn = Mp3Stream.Read();
     }
     if (dataToSendIn.Length > 0)
     {
         devices?.OnRecordingDataAvailable(dataToSendIn, formatIn, reduceLagThreshold, StreamFormatSelected);
     }
 }
Beispiel #20
0
        /// <summary>
        /// The user changed the stream format in the user interface.
        /// Restart streaming in the new format.
        /// </summary>
        /// <param name="formatIn">the chosen format</param>
        public void SetStreamFormat(SupportedStreamFormat formatIn)
        {
            if (devices == null)
            {
                return;
            }

            if (formatIn != StreamFormatSelected)
            {
                StreamFormatSelected = formatIn;
                Mp3Stream            = null;

                devices.Stop();
                devices.Start();
            }
        }
Beispiel #21
0
 public void Stop()
 {
     if (mp3Stream == null)
     {
         return;
     }
     if (secondaryBuffer == null)
     {
         return;
     }
     Playing = false;
     bufferDescription.Dispose();
     secondaryBuffer.Dispose();
     mp3Stream.Dispose();
     mp3Stream = null;
 }
Beispiel #22
0
        public bool FillFromStream(Mp3Stream stream)
        {
            if (stream == null)
                return false;

            int size = stream.Read(byteBuffer, BufferSize);
            bool dataAvailable = size > 0;
            if (dataAvailable)
            {
                XAudioBuffer.AudioDataPointer = GetBufferHandle();
                XAudioBuffer.AudioBytes = size;
                int blockAlign = stream.Channels * 2;
                XAudioBuffer.PlayLength = size / blockAlign;
            }

            return dataAvailable;
        }
Beispiel #23
0
        /// <summary>
        /// The user changed the stream format in the user interface.
        /// Restart streaming in the new format.
        /// </summary>
        /// <param name="formatIn">the chosen format</param>
        public void SetStreamFormat(SupportedStreamFormat formatIn)
        {
            if (devices == null)
            {
                return;
            }

            if (formatIn != StreamFormatSelected)
            {
                logger.Log($"Set stream format to {formatIn}");
                StreamFormatSelected = formatIn;
                Mp3Stream            = null;

                devices.Stop();
                devices.Start();
            }
        }
Beispiel #24
0
        void DoLoading(object obj)
        {
            Wavefile  wave   = m_Wavefile;
            Mp3Stream stream = (Mp3Stream)obj;

            BlockArray <Sample> array = wave.m_Samples;

            //SafeStream safeStream = new SafeStream(stream);

            Sample[] sample = new Sample[10000];
            byte[]   buffer = new byte[sample.Length * 4];

            Thread.Sleep(1000);

            while (true)             //safeStream.Position < safeStream.Length)
            {
                //int count;
                //int countMax = (int)Math.Min(1024, (safeStream.Length - safeStream.Position)/4);
                //for (count=0; count <countMax; count ++)
                //{
                //    //sample[count] = new Sample(ReadI2(safeStream), ReadI2(safeStream));
                //    sample[count] = ReadSI2(safeStream);
                //}

                int byteCount = stream.Read(buffer, 0, buffer.Length);
                if (byteCount == 0)
                {
                    break;
                }

                int sampleCount = byteCount / 4;

                for (int i = 0, j = 0; i < sampleCount; i++, j += 4)
                {
                    sample[i] = new Sample((short)(buffer[j] | buffer[j + 1] << 8),
                                           (short)(buffer[j + 2] | buffer[j + 3] << 8));
                }

                array.Write(sample, 0, sampleCount);
                Thread.Sleep(0);
            }

            stream.Dispose();
            wave.FinishedLoading = true;
        }
        public override SongTagFile PopulateSongTag(string fileName, TagOption tagOption = TagOption.All)
        {
            using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                using (Mp3Stream mp3Stream = new Mp3Stream(fileStream, Mp3Permissions.ReadWrite))
                {
                    var id3Tag = GetTagFromStream(mp3Stream);

                    if (id3Tag != null)
                    {
                        var song = new SongTagFile();
                        song.Duration = mp3Stream.Audio.Duration.ToString();
                        song.BitRate  = mp3Stream.Audio.Bitrate;
                        return(CreateSongTag(song, id3Tag, tagOption));
                    }
                }

            return(null);
        }
        private async Task <BitmapImage> GetAlbumImage(Stream path)
        {
            BitmapImage bitmapImage = new BitmapImage(new Uri("ms-appx:///Image/DefaultImage.png", UriKind.RelativeOrAbsolute));
            var         mp3         = new Mp3Stream(path);
            var         tags        = mp3.GetAllTags();
            var         picture     = tags[0].Pictures[0].PictureData;

            if (picture.Any())
            {
                using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(picture.AsBuffer());

                    stream.Seek(0);
                    await bitmapImage.SetSourceAsync(stream);
                }
            }
            return(bitmapImage);
        }
Beispiel #27
0
 public void ReadID3(Stream stream)
 {
     try {
         using (var mp3 = new Mp3Stream(stream)) {
             var tags = new List <Id3Tag>(mp3.GetAllTags());
             if (tags.Count > 0)
             {
                 var firstTag = tags.First();
                 var title    = firstTag.Title.Value;
                 if (String.IsNullOrWhiteSpace(title))
                 {
                     title = "crazy";
                 }
                 //return new SongInfo(title, firstTag.Artists.Value, firstTag.Album.Value);
             }
         }
     } catch (IndexOutOfRangeException iore) {
         // maybe thrown if the file is cocked up and id3 tags cannot be read
         Debug.WriteLine(iore.Message);
     }
 }
Beispiel #28
0
        protected override void OnBufferInitializing()
        {
            Mp3Stream stream = Stream as Mp3Stream;

            if (stream == null)
            {
                throw new ApplicationException("The stream used by the StreamedMp3Sound class should be of type Mp3Stream.");
            }

            if (stream.Frequency < 0)
            {
                if (stream.DecodeFrames(1) == 0)
                {
                    //  throw new Exception("Could not decode");
                }
            }
            if (stream.Frequency > 0 && stream.ChannelCount > 0)
            {
                this.WaveFormat = SoundUtil.CreateWaveFormat(stream.Frequency, 16, stream.ChannelCount);
            }
        }
Beispiel #29
0
        public void ReadAlbumArt()
        {
            Id3Tag tag;

            using (FileStream stream = new FileStream(CurrentTrack.LocalPath, FileMode.Open, FileAccess.Read))
                using (Mp3Stream mp3 = new Mp3Stream(stream))
                    tag = mp3.GetTag(Id3TagFamily.FileStartTag);
            BitmapImage bitmapImage;

            try
            {
                PictureFrame image = tag.Pictures.FirstOrDefault();
                byte[]       bytes = image.PictureData;

                try
                {
                    bitmapImage = new BitmapImage();
                    using (MemoryStream memory = new MemoryStream(bytes))
                    {
                        bitmapImage.BeginInit();
                        bitmapImage.StreamSource = memory;
                        bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                        bitmapImage.EndInit();
                    }
                    ImageStretch = Stretch.UniformToFill;
                }
                catch (Exception)
                {
                    bitmapImage  = GetBitmapImage(new Uri("pack://application:,,,/Images/TakaneError.png", UriKind.Absolute));
                    ImageStretch = Stretch.None;
                }
            }
            catch (NullReferenceException)
            {
                bitmapImage  = GetBitmapImage(new Uri("pack://application:,,,/Images/TakaneNoImage.png", UriKind.Absolute));
                ImageStretch = Stretch.None;
            }
            AlbumArt = bitmapImage;
        }
        /// <summary>
        /// Retrieves either ID3V2 or Id3V1 tag
        /// </summary>
        /// <param name="mp3Stream">The MP3 stream.</param>
        /// <returns></returns>
        /// <exception cref="NullReferenceException"></exception>
        private Id3Tag GetTagFromStream(Mp3Stream mp3Stream)
        {
            Id3.Id3Tag tag = null;

            //Exit, we have no tags
            if (!mp3Stream.HasTags)
            {
                return(tag);
            }

            //Get the file start tag which is ID3v2
            tag = mp3Stream.GetTag(Id3TagFamily.FileStartTag);
            if (tag == null)
            {
                tag = mp3Stream.GetTag(Id3TagFamily.FileEndTag);

                if (tag == null)
                {
                    throw new NullReferenceException($"Couldn't parse tag for file");
                }
            }

            //Get the file start tag which is ID3v2
            else if (!tag.Year.IsAssigned)
            {
                var tagForYear = mp3Stream.GetTag(Id3TagFamily.FileEndTag);
                if (tagForYear != null)
                {
                    if (tagForYear.Year.IsAssigned)
                    {
                        var year = tagForYear.Year.AsDateTime.Value;
                        tag.Year.Value = Convert.ToString(year.Year);
                    }
                }
            }

            return(tag);
        }
Beispiel #31
0
        public override Wavefile Load(Stream fileStream)
        {
            Mp3Stream mp3Stream = new Mp3Stream(fileStream);

            if (mp3Stream.Frequency < 0)
            {
                mp3Stream.DecodeFrames(1);
            }
            if (!(mp3Stream.Frequency > 0 && mp3Stream.ChannelCount > 0))
            {
                throw new InvalidFileFormatException("No frequency/channel information");
            }

            if (mp3Stream.Format != SoundFormat.Pcm16BitStereo)
            {
                throw new NotImplementedException("Only stereo MP3 supported");
            }

            Wavefile wave = new Wavefile();

            wave.m_SampleRate = mp3Stream.Frequency;
            wave.m_Samples    = new BlockArray <Sample>(12);

            m_Wavefile = wave;

            //new DoLoadingDelegate(DoLoading).BeginInvoke(wave, mp3Stream, new AsyncCallback(FinishedLoadingCallback), wave);

            Thread loadThread = new Thread(new ParameterizedThreadStart(DoLoading));

            loadThread.IsBackground = true;
            loadThread.Start(mp3Stream);

            //DoLoading(wave, mp3Stream);

            return(wave);
        }
Beispiel #32
0
 public Mp3StreamId sceMp3ReserveMp3Handle(SceMp3InitArg* Mp3Arguments)
 {
     var Mp3Handle = new Mp3Stream();
     return Mp3Handles.Create(Mp3Handle);
 }
Beispiel #33
0
 public Mp3AudioStream(Stream source)
 {
     stream = new Mp3Stream(source);
 }
Beispiel #34
0
 /// <summary>
 /// Clear the audio data in the mp3 encoder.
 /// </summary>
 public void ClearMp3Buffer()
 {
     Mp3Stream = null;
 }
Beispiel #35
0
 public int sceMp3GetLoopNum(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #36
0
 public int sceMp3GetBitRate(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #37
0
 public bool sceMp3CheckStreamDataNeeded(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #38
0
        public void ReadAlbumArt()
        {
            Id3Tag tag;
            using (FileStream stream = new FileStream(CurrentTrack.LocalPath, FileMode.Open, FileAccess.Read))
            using (Mp3Stream mp3 = new Mp3Stream(stream))
                tag = mp3.GetTag(Id3TagFamily.FileStartTag);
            BitmapImage bitmapImage;
            try
            {
                PictureFrame image = tag.Pictures.FirstOrDefault();
                byte[] bytes = image.PictureData;

                try
                {
                    bitmapImage = new BitmapImage();
                    using (MemoryStream memory = new MemoryStream(bytes))
                    {
                        bitmapImage.BeginInit();
                        bitmapImage.StreamSource = memory;
                        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                        bitmapImage.EndInit();
                    }
                    ImageStretch = Stretch.UniformToFill;
                }
                catch (Exception)
                {
                    bitmapImage = GetBitmapImage(new Uri("pack://application:,,,/Images/TakaneError.png", UriKind.Absolute));
                    ImageStretch = Stretch.None;
                }
            }
            catch (NullReferenceException)
            {
                bitmapImage = GetBitmapImage(new Uri("pack://application:,,,/Images/TakaneNoImage.png", UriKind.Absolute));
                ImageStretch = Stretch.None;
            }
            AlbumArt = bitmapImage;
        }
Beispiel #39
0
 public override void Dispose()
 {
     AL.DeleteBuffers(buffers);
     AL.DeleteSource(source);
     musicStream = null;
 }
 public int sceMp3GetLoopNum(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #41
0
        public static void Read(string path, ModelView.SoundModelView modelView)
        {
            if (!File.Exists(path))
                return;

            File.SetAttributes(path, FileAttributes.Normal);

            try
            {
                Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                Mp3Stream mp3 = new Mp3Stream(stream);

                if (!mp3.HasTags)
                {
                    stream.Close();
                    ComputeFromFileName(path, modelView.Sound);
                    return;
                }

                var tags = mp3.GetAllTags();

                foreach (var tag in tags)
                    if (tag != null)
                    {
                        modelView.Sound.artist = tag.Artists.Value;
                        modelView.Sound.title = tag.Title.Value;
                        modelView.Photo = GetPicture(tag);
                        //int.TryParse(tag.BeatsPerMinute.Value, out modelView.duration);
                        break;
                    }
                stream.Close();

            }//try
            catch (Exception)
            {
                ComputeFromFileName(path, modelView.Sound);
            }
        }
        public Dictionary<string, string> GetMetaData(string path)
        {
            Dictionary<string, string> list = new Dictionary<string, string>();
            path = path.Replace("|", "\\");
            using (var stream = new FileStream(path, FileMode.Open))
            {
                Mp3Stream m = new Mp3Stream(stream);
                if (m.HasTags)
                {
                    var tag = m.GetAllTags();

                    list.Add("Artist", tag[0].Artists.Value);
                    list.Add("Album", tag[0].Album.Value);
                    list.Add("Genre", GetGenre(tag[0].Genre.Value));
                    list.Add("Title", tag[0].Title.Value);
                    list.Add("Track", tag[0].Track.Value);
                }
            }
            return list;
        }
Beispiel #43
0
 public int sceMp3ResetPlayPosition(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #44
0
 public int sceMp3SetLoopNum(Mp3Stream Mp3Stream, int NumberOfLoops)
 {
     throw (new NotImplementedException());
 }
Beispiel #45
0
        public void Start()
        {
            Stream = new Mp3Stream(Path);
            Stream.DecodeFrames(1);
            var freq = Stream.Frequency;

            lock (ControlLock)
            {
                if (Disposed)
                {
                    return;
                }
                Inst               = new DynamicSoundEffectInstance(freq, AudioChannels.Stereo);
                Inst.IsLooped      = false;
                Inst.BufferNeeded += SubmitBufferAsync;
                if (_State == SoundState.Playing)
                {
                    Inst.Play();
                }
                else if (_State == SoundState.Paused)
                {
                    Inst.Play();
                    Inst.Pause();
                }
                Inst.Volume = _Volume;
                Inst.Pan    = _Pan;
                Requests    = 2;
            }

            //SubmitBuffer(null, null);
            //SubmitBuffer(null, null);

            DecoderThread = new Thread(() =>
            {
                try
                {
                    while (Active && MainThread.IsAlive)
                    {
                        DecodeNext.WaitOne(128);
                        bool go;
                        lock (this) go = Requests > 0;
                        while (go)
                        {
                            var buf  = new byte[262144];// 524288];
                            var read = Stream.Read(buf, 0, buf.Length);
                            lock (this)
                            {
                                Requests--;
                                NextBuffers.Add(buf);
                                NextSizes.Add(read);
                                if (read == 0)
                                {
                                    EndOfStream = true;
                                    BufferDone.Set();
                                    return;
                                }
                                BufferDone.Set();
                            }
                            lock (this) go = Requests > 0;
                        }
                    }
                }
                catch (Exception e) { }
            });
            DecoderThread.Start();
            DecodeNext.Set();
        }
Beispiel #46
0
 public int sceMp3Decode(Mp3Stream Mp3Stream, uint OutputPcmPointer)
 {
     throw (new NotImplementedException());
 }
Beispiel #47
0
 public int sceMp3GetMp3ChannelNum(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #48
0
 public int sceMp3GetInfoToAddStreamData(Mp3Stream Mp3Stream, uint Mp3BufferPointer, uint mp3BufToWritePtr, uint mp3PosPtr)
 {
     throw (new NotImplementedException());
 }
Beispiel #49
0
 public int sceMp3GetSamplingRate(Mp3Stream Mp3Stream)
 {
     return Mp3Stream.SamplingRate;
 }
Beispiel #50
0
 public int sceMp3GetMaxOutputSample(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #51
0
 public int sceMp3GetSumDecodedSample(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
 public void Tag()
 {
     if (this.AudioMedia != null)
     {
         try
         {
             using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
             {
                 var streamFile = store.OpenFile(Path.Combine(this.MediaSupportService.GetStorageDirectory(), this.AudioMedia.FilesystemId), FileMode.Open);
                 using (var streamMP3 = new Mp3Stream(streamFile))
                 {
                     Id3Tag tag = streamMP3.GetTag(Id3TagFamily.FileStartTag);
                     this.CurrentAlbum = tag.Album ?? string.Empty;
                     this.CurrentArtist = tag.Artists != null ? tag.Artists.Value ?? string.Empty : string.Empty;
                     this.SongTitle = tag.Title;
                 }
             }
         }
         catch (Exception e)
         {
             this.DialogViewService.MessageBoxOk(Main.Error, MusicList.TagError);
         }
     }
 }
Beispiel #53
0
 public int sceMp3Init(Mp3Stream Mp3Stream)
 {
     throw (new NotImplementedException());
 }
Beispiel #54
0
 public Mp3AudioStream(Stream source)
 {
     stream = new Mp3Stream(source);
 }
Beispiel #55
0
 public int sceMp3NotifyAddStreamData(Mp3Stream Mp3Stream, int Size)
 {
     Mp3Stream.AddStreamData(
         PointerUtils.PointerToByteArray((byte*)Mp3Stream.Mp3Arguments->Mp3BufferPointer.GetPointer(Memory, Size), Size)
     );
     return 0;
 }
Beispiel #56
0
 public int sceMp3ReleaseMp3Handle(Mp3Stream Mp3Stream)
 {
     Mp3Stream.RemoveUid(InjectContext);
     return 0;
 }
Beispiel #57
0
        void Load(System.IO.Stream stream)
        {
            //if (secondaryBuffer == null)
            //{
            //    return;
            //}
            //if (secondaryBuffer.Disposed)
            //{
            //    return;
            //}
            if (Playing)
            {
                secondaryBuffer.Stop();
                Playing = false;
            }
            mp3Stream = new Mp3Stream(stream);

            mp3Stream.Read(buff, 0, 512);
            mp3Stream.Position = 0;

            waveFormat.BitsPerSample         = 16;
            waveFormat.Channels              = mp3Stream.ChannelCount;
            waveFormat.SamplesPerSecond      = mp3Stream.Frequency;
            waveFormat.FormatTag             = WaveFormatTag.Pcm;
            waveFormat.BlockAlign            = (short)(waveFormat.Channels * (waveFormat.BitsPerSample / 8));
            waveFormat.AverageBytesPerSecond = waveFormat.SamplesPerSecond * waveFormat.BlockAlign;

            wholeSize = (int)(waveFormat.AverageBytesPerSecond * TimeSpan.FromSeconds(0.2).TotalSeconds);

            bufferDescription               = new BufferDescription(waveFormat);
            bufferDescription.BufferBytes   = wholeSize;
            bufferDescription.GlobalFocus   = true;
            bufferDescription.ControlVolume = true;

            secondaryBuffer        = new SecondaryBuffer(bufferDescription, game.Devices.DSoundDev);
            secondaryBuffer.Volume = volum;

            #region useless code area
            //autoResetEvent = new System.Threading.AutoResetEvent(false);

            //notify = new Notify(secondaryBuffer);

            //System.Reflection.MethodInfo methodInfo;
            //methodInfo = typeof(SoundManager).GetMethod("fillBack");

            //bufferPositionNotify = new BufferPositionNotify[2];
            //bufferPositionNotify[0] = new BufferPositionNotify();
            //bufferPositionNotify[0].Offset = 0;
            //bufferPositionNotify[0].EventNotifyHandle = this.GetType().GetMethod("fillBack", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).MethodHandle.Value;
            //bufferPositionNotify[1] = new BufferPositionNotify();
            //bufferPositionNotify[1].Offset = halfSize;
            //bufferPositionNotify[1].EventNotifyHandle = this.GetType().GetMethod("fillFore", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).MethodHandle.Value;

            //bufferPositionNotify = new BufferPositionNotify[2];
            //bufferPositionNotify[0] = new BufferPositionNotify();
            //bufferPositionNotify[0].Offset = 0;
            //bufferPositionNotify[0].EventNotifyHandle = autoResetEvent.Handle;
            //bufferPositionNotify[1] = new BufferPositionNotify();
            //bufferPositionNotify[1].Offset = halfSize;
            //bufferPositionNotify[1].EventNotifyHandle = autoResetEvent.Handle;

            //notify.SetNotificationPositions(bufferPositionNotify);
            #endregion
        }