Exemplo n.º 1
0
Arquivo: Project.cs Projeto: daisy/obi
        /// <summary>
        /// Import an audio file to the project by creating a new node with audio from the file.
        /// The node is created but not actually added but a command is returned.
        /// </summary>
        /// <param name="path">Full path to the audio file to import.</param>
        /// <param name="contextNode">The context node before which to import the audio file.
        /// If null, add at the end.</param>
        /// <returns>The command for adding the node.</returns>
        public Commands.AddTreeNode ImportAudioFileCommand(string path, TreeNode contextNode)
        {
            Stream      input = File.OpenRead(path);
            PCMDataInfo info  = PCMDataInfo.parseRiffWaveHeader(input);

            input.Close();
            getPresentation().getMediaDataManager().getDefaultPCMFormat().setBitDepth(info.getBitDepth());
            getPresentation().getMediaDataManager().getDefaultPCMFormat().setNumberOfChannels(info.getNumberOfChannels());
            getPresentation().getMediaDataManager().getDefaultPCMFormat().setSampleRate(info.getSampleRate());
            AudioMediaData data = (AudioMediaData)
                                  getPresentation().getMediaDataFactory().createMediaData(typeof(AudioMediaData));

            data.appendAudioDataFromRiffWave(path);
            ManagedAudioMedia media = (ManagedAudioMedia)getPresentation().getMediaFactory().createAudioMedia();

            media.setMediaData(data);
            Channel          audio = GetSingleChannelByName(AUDIO_CHANNEL_NAME);
            ChannelsProperty prop  = getPresentation().getPropertyFactory().createChannelsProperty();

            prop.setMedia(audio, media);
            TreeNode node = getPresentation().getTreeNodeFactory().createNode();

            node.setProperty(prop);
            TreeNode root = getPresentation().getRootNode();

            Commands.AddTreeNode command = new Commands.AddTreeNode(node, root,
                                                                    contextNode == null ? root.getChildCount() : contextNode.getParent().indexOf(contextNode));
            return(command);
        }
Exemplo n.º 2
0
        private void OnOpenFile(object sender, RoutedEventArgs e)
        {
            if (m_Player.State == AudioPlayerState.Playing)
            {
                m_Player.Pause();
            }
            else if (m_Player.State == AudioPlayerState.Paused || m_Player.State == AudioPlayerState.Stopped)
            {
                m_Player.Resume();
            }

            OpenFileDialog dlg = new OpenFileDialog();

            dlg.FileName   = "audio"; // Default file name
            dlg.DefaultExt = ".wav";  // Default file extension
            dlg.Filter     = "WAV files (.wav)|*.wav;*.aiff";
            bool?result = dlg.ShowDialog();

            if (result == false)
            {
                return;
            }

            if (m_Player.State != AudioPlayerState.NotReady && m_Player.State != AudioPlayerState.Stopped)
            {
                m_Player.Stop();
            }

            FilePath = dlg.FileName;

            m_pcmFormat = null;

            if (PeakMeterPathCh1.Data != null)
            {
                ((StreamGeometry)PeakMeterPathCh1.Data).Clear();
            }
            if (PeakMeterPathCh2.Data != null)
            {
                ((StreamGeometry)PeakMeterPathCh2.Data).Clear();
            }

            PeakOverloadCountCh1 = 0;
            PeakOverloadCountCh2 = 0;

            loadWaveForm();

            m_Player.Play(mCurrentAudioStreamProvider,
                          m_pcmFormat.GetDuration(m_pcmFormat.DataLength), m_pcmFormat);
        }
Exemplo n.º 3
0
        private void mPlayButton_Click(object sender, EventArgs e)
        {
            mPlaybackDevice.stopPlayback();
            if (mInputFilesListView.Items.Count == 0)
            {
                MessageBox.Show(this, "There are no input files to play", "Play");
                return;
            }
            /* Playback of all files using both SubStream and SequenceStream */
            List <Stream> ifStreams = new List <Stream>(mInputFilesListView.Items.Count);

            foreach (ListViewItem inputFileItem in mInputFilesListView.Items)
            {
                FileStream  ifs      = new FileStream(inputFileItem.SubItems[2].Text, FileMode.Open, FileAccess.Read);
                PCMDataInfo pcmInfo  = PCMDataInfo.ParseRiffWaveHeader(ifs);
                long        startPos = ifs.Position;
                ifs.Position = 0;
                SubStream subIfs = new SubStream(ifs, startPos, pcmInfo.DataLength);
                ifStreams.Add(subIfs);
            }
            mPCMInputStream = new SequenceStream(ifStreams);
            mPlaybackDevice.play(mPCMInputStream);
        }
Exemplo n.º 4
0
        private void loadWaveForm()
        {
            //DrawingGroup dGroup = VisualTreeHelper.GetDrawing(WaveFormCanvas);

            bool wasPlaying = (m_Player.State == AudioPlayerState.Playing);

            if (m_Player.State != AudioPlayerState.NotReady)
            {
                if (wasPlaying)
                {
                    m_Player.Pause();
                }
            }

            if (mCurrentAudioStreamProvider() == null)
            {
                return;
            }


            if (m_pcmFormat == null)
            {
                m_FilePlayStream.Position = 0;
                m_FilePlayStream.Seek(0, SeekOrigin.Begin);
                m_pcmFormat = PCMDataInfo.ParseRiffWaveHeader(m_FilePlayStream);
                m_StreamRiffHeaderEndPos = m_FilePlayStream.Position;
            }
            else
            {
                m_FilePlayStream.Position = m_StreamRiffHeaderEndPos;
                m_FilePlayStream.Seek(m_StreamRiffHeaderEndPos, SeekOrigin.Begin);
            }

            if (m_pcmFormat.BitDepth != 16)
            {
                return;
            }

            if (m_pcmFormat.NumberOfChannels == 1)
            {
                PeakOverloadLabelCh2.Visibility = Visibility.Collapsed;
            }
            else
            {
                PeakOverloadLabelCh2.Visibility = Visibility.Visible;
            }


            ushort frameSize       = (ushort)(m_pcmFormat.NumberOfChannels * m_pcmFormat.BitDepth / 8);
            double samplesPerPixel = Math.Ceiling(m_pcmFormat.DataLength
                                                  / (double)frameSize
                                                  / WaveFormCanvas.ActualWidth * m_pcmFormat.NumberOfChannels);

            m_bytesPerPixel = samplesPerPixel * frameSize / m_pcmFormat.NumberOfChannels;

            byte[]  bytes   = new byte[(int)m_bytesPerPixel];
            short[] samples = new short[(int)samplesPerPixel];

            StreamGeometry        geometryCh1 = new StreamGeometry();
            StreamGeometryContext sgcCh1      = geometryCh1.Open();

            StreamGeometry        geometryCh2 = null;
            StreamGeometryContext sgcCh2      = null;

            if (m_pcmFormat.NumberOfChannels > 1)
            {
                geometryCh2 = new StreamGeometry();
                sgcCh2      = geometryCh2.Open();
            }

            double height = WaveFormImage.Height;

            if (m_pcmFormat.NumberOfChannels > 1)
            {
                height /= 2;
            }

            for (double x = 0; x < WaveFormImage.Width; ++x)
            {
                int read = m_FilePlayStream.Read(bytes, 0, (int)m_bytesPerPixel);
                if (read <= 0)
                {
                    continue;
                }
                Buffer.BlockCopy(bytes, 0, samples, 0, read);

                short min = short.MaxValue;
                short max = short.MinValue;
                for (int channel = 0; channel < m_pcmFormat.NumberOfChannels; channel++)
                {
                    int limit = (int)Math.Ceiling(read / (float)frameSize);

                    for (int i = channel; i < limit; i += m_pcmFormat.NumberOfChannels)
                    {
                        if (samples[i] < min)
                        {
                            min = samples[i];
                        }
                        if (samples[i] > max)
                        {
                            max = samples[i];
                        }
                    }

                    double y1 = height
                                - ((min - short.MinValue) * height)
                                / ushort.MaxValue;

                    if (channel == 0)
                    {
                        sgcCh1.BeginFigure(new Point(x, y1), false, false);
                    }
                    else
                    {
                        y1 += height;
                        sgcCh2.BeginFigure(new Point(x, y1), false, false);
                    }


                    double y2 = height
                                - ((max - short.MinValue) * height)
                                / ushort.MaxValue;
                    if (channel == 0)
                    {
                        sgcCh1.LineTo(new Point(x, y2), true, false);
                    }
                    else
                    {
                        y2 += height;
                        sgcCh2.LineTo(new Point(x, y2), true, false);
                    }
                }
            }

            m_FilePlayStream.Close();
            m_FilePlayStream = null;

            sgcCh1.Close();
            if (m_pcmFormat.NumberOfChannels > 1)
            {
                sgcCh2.Close();
            }


            DrawingImage drawImg = new DrawingImage();

            //
            geometryCh1.Freeze();
            GeometryDrawing geoDraw1 = new GeometryDrawing(Brushes.LimeGreen, new Pen(Brushes.LimeGreen, 1.0), geometryCh1);

            geoDraw1.Freeze();
            //
            GeometryDrawing geoDraw2 = null;

            if (m_pcmFormat.NumberOfChannels > 1)
            {
                geometryCh2.Freeze();
                geoDraw2 = new GeometryDrawing(Brushes.LimeGreen, new Pen(Brushes.LimeGreen, 1.0), geometryCh2);
                geoDraw2.Freeze();
            }
            //
            if (m_pcmFormat.NumberOfChannels > 1)
            {
                DrawingGroup drawGrp = new DrawingGroup();
                drawGrp.Children.Add(geoDraw1);
                drawGrp.Children.Add(geoDraw2);
                drawGrp.Freeze();
                drawImg.Drawing = drawGrp;
            }
            else
            {
                drawImg.Drawing = geoDraw1;
            }
            drawImg.Freeze();
            WaveFormImage.Source = drawImg;


            m_WaveFormLoadingAdorner.Visibility = Visibility.Hidden;

            if (wasPlaying)
            {
                m_Player.Resume();
            }
        }
Exemplo n.º 5
0
        private void parseSmil(string fullSmilPath)
        {
            Presentation presentation = m_Project.GetPresentation(0);

            string dirPath = Path.GetDirectoryName(m_Book_FilePath);

            XmlDocument smilXmlDoc = readXmlDocument(fullSmilPath);

            XmlNodeList listOfAudioNodes = smilXmlDoc.GetElementsByTagName("audio");

            if (listOfAudioNodes != null)
            {
                foreach (XmlNode audioNode in listOfAudioNodes)
                {
                    XmlAttributeCollection attributeCol = audioNode.Attributes;

                    if (attributeCol != null)
                    {
                        XmlNode attrAudioSrc = attributeCol.GetNamedItem("src");
                        if (attrAudioSrc != null && !String.IsNullOrEmpty(attrAudioSrc.Value))
                        {
                            XmlNode parent = audioNode.ParentNode;
                            if (parent != null && parent.Name == "a")
                            {
                                parent = parent.ParentNode;
                            }

                            if (parent != null)
                            {
                                XmlNodeList listOfAudioPeers = parent.ChildNodes;
                                foreach (XmlNode peerNode in listOfAudioPeers)
                                {
                                    if (peerNode.NodeType == XmlNodeType.Element && peerNode.Name == "text")
                                    {
                                        XmlAttributeCollection peerAttrs = peerNode.Attributes;

                                        if (peerAttrs != null)
                                        {
                                            XmlNode attrTextSrc = peerAttrs.GetNamedItem("src");
                                            if (attrTextSrc != null && !String.IsNullOrEmpty(attrTextSrc.Value))
                                            {
                                                int index = attrTextSrc.Value.LastIndexOf('#');
                                                if (index < (attrTextSrc.Value.Length - 1))
                                                {
                                                    string        dtbookFragmentId = attrTextSrc.Value.Substring(index + 1);
                                                    core.TreeNode tNode            = getTreeNodeWithXmlElementId(dtbookFragmentId);
                                                    if (tNode != null)
                                                    {
                                                        AbstractAudioMedia existingAudioMedia = tNode.GetAudioMedia();
                                                        if (existingAudioMedia != null)
                                                        {
                                                            //Ignore.
                                                            //System.Diagnostics.Debug.Fail("TreeNode already has media ??");
                                                        }

                                                        XmlNode attrClipBegin = attributeCol.GetNamedItem("clipBegin");
                                                        XmlNode attrClipEnd   = attributeCol.GetNamedItem("clipEnd");

                                                        Media media = null;
                                                        if (attrAudioSrc.Value.EndsWith("wav"))
                                                        {
                                                            string fullWavPath = Path.Combine(dirPath,
                                                                                              attrAudioSrc.Value);

                                                            PCMDataInfo pcmInfo   = null;
                                                            Stream      wavStream = null;
                                                            try
                                                            {
                                                                wavStream = File.Open(fullWavPath, FileMode.Open,
                                                                                      FileAccess.Read, FileShare.Read);
                                                                pcmInfo = PCMDataInfo.ParseRiffWaveHeader(wavStream);
                                                                presentation.MediaDataManager.DefaultPCMFormat = pcmInfo.Copy();
                                                                TimeDelta duration = new TimeDelta(pcmInfo.Duration);

                                                                Time clipB = Time.Zero;
                                                                Time clipE = Time.MaxValue;

                                                                if (attrClipBegin != null &&
                                                                    !string.IsNullOrEmpty(attrClipBegin.Value))
                                                                {
                                                                    clipB = new Time(TimeSpan.Parse(attrClipBegin.Value));
                                                                }
                                                                if (attrClipEnd != null &&
                                                                    !string.IsNullOrEmpty(attrClipEnd.Value))
                                                                {
                                                                    clipE = new Time(TimeSpan.Parse(attrClipEnd.Value));
                                                                }
                                                                if (!clipB.IsEqualTo(Time.Zero) || !clipE.IsEqualTo(Time.MaxValue))
                                                                {
                                                                    duration = clipE.GetTimeDelta(clipB);
                                                                }
                                                                long byteOffset = 0;
                                                                if (!clipB.IsEqualTo(Time.Zero))
                                                                {
                                                                    byteOffset = pcmInfo.GetByteForTime(clipB);
                                                                }
                                                                if (byteOffset > 0)
                                                                {
                                                                    wavStream.Seek(byteOffset, SeekOrigin.Current);
                                                                }

                                                                presentation.MediaDataFactory.DefaultAudioMediaDataType =
                                                                    typeof(WavAudioMediaData);

                                                                WavAudioMediaData mediaData =
                                                                    (WavAudioMediaData)
                                                                    presentation.MediaDataFactory.CreateAudioMediaData();
                                                                mediaData.InsertAudioData(wavStream, Time.Zero, duration);

                                                                media = presentation.MediaFactory.CreateManagedAudioMedia();
                                                                ((ManagedAudioMedia)media).AudioMediaData = mediaData;
                                                            }
                                                            finally
                                                            {
                                                                if (wavStream != null)
                                                                {
                                                                    wavStream.Close();
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            media = presentation.MediaFactory.CreateExternalAudioMedia();
                                                            ((ExternalAudioMedia)media).Src = attrAudioSrc.Value;
                                                            if (attrClipBegin != null &&
                                                                !string.IsNullOrEmpty(attrClipBegin.Value))
                                                            {
                                                                ((ExternalAudioMedia)media).ClipBegin =
                                                                    new Time(TimeSpan.Parse(attrClipBegin.Value));
                                                            }
                                                            if (attrClipEnd != null &&
                                                                !string.IsNullOrEmpty(attrClipEnd.Value))
                                                            {
                                                                ((ExternalAudioMedia)media).ClipEnd =
                                                                    new Time(TimeSpan.Parse(attrClipEnd.Value));
                                                            }
                                                        }

                                                        ChannelsProperty chProp = tNode.GetProperty <ChannelsProperty>();
                                                        if (chProp == null)
                                                        {
                                                            chProp =
                                                                presentation.PropertyFactory.CreateChannelsProperty();
                                                            tNode.AddProperty(chProp);
                                                        }
                                                        chProp.SetMedia(m_audioChannel, media);
                                                        break; // scan peers to audio node
                                                    }
                                                    else
                                                    {
                                                        System.Diagnostics.Debug.Fail("XmlProperty with ID not found ??");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        private void mAddInputFileButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter          = "WAVE PCM (*.wav)|*.wav";
            ofd.Title           = "Add WAVE PCM Input Files";
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.Multiselect     = true;
            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                List <ListViewItem> addedItems = new List <ListViewItem>();
                foreach (string file in ofd.FileNames)
                {
                    FileStream  fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Write);
                    PCMDataInfo pcmInfo;
                    try
                    {
                        pcmInfo = PCMDataInfo.ParseRiffWaveHeader(fs);
                    }
                    catch (Exception err)
                    {
                        if (MessageBox.Show(
                                this,
                                String.Format("Could not parse wave file {0}: {1}", file, err.Message),
                                "Add files",
                                MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            continue;
                        }
                        else
                        {
                            return;
                        }
                    }
                    finally
                    {
                        fs.Close();
                    }
                    if (mInputFilesListView.Items.Count == 0)
                    {
                        mPlaybackDevice.setBitDepth(pcmInfo.BitDepth);
                        mPlaybackDevice.setSampleRate(pcmInfo.SampleRate);
                        mPlaybackDevice.setNumberOfChannels(pcmInfo.NumberOfChannels);
                        mHorizontalPPMeter.NumberOfChannels = pcmInfo.NumberOfChannels;
                        mVerticalPPMeter.NumberOfChannels   = pcmInfo.NumberOfChannels;
                        UpdatePlaybackSpeedControl();
                    }
                    else
                    {
                        if (
                            mPlaybackDevice.getBitDepth() != pcmInfo.BitDepth ||
                            mPlaybackDevice.getSampleRate() != pcmInfo.SampleRate ||
                            mPlaybackDevice.getNumberOfChannels() != pcmInfo.NumberOfChannels)
                        {
                            string msg = String.Format(
                                "Wave file {0} is not compatible with the previously added files.\n"
                                + "Must have {1:0} channels, sample rate {2:0} and bit depth {3:0}",
                                file,
                                mPlaybackDevice.getNumberOfChannels(),
                                mPlaybackDevice.getSampleRate(),
                                mPlaybackDevice.getBitDepth());
                            if (MessageBox.Show(this, msg, "Add files", MessageBoxButtons.OKCancel) == DialogResult.OK)
                            {
                                continue;
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                    string[] itemArr = new string[] { Path.GetFileName(file), FormatTimeSpan(pcmInfo.Duration.TimeDeltaAsTimeSpan), file };
                    addedItems.Add(new ListViewItem(itemArr));
                }
                mInputFilesListView.Items.AddRange(addedItems.ToArray());
            }
            UpdateInputFilesButtons(mPlaybackDevice.getState());
        }
Exemplo n.º 7
0
        private void OpenFile()
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter          = "WAVE PCM (*.wav)|*.wav";
            ofd.Multiselect     = false;
            ofd.AddExtension    = true;
            ofd.Title           = "Open Wave File";
            ofd.CheckFileExists = false;
            ofd.CheckPathExists = true;
            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                if (ofd.FileName != mFileTextBox.Text)
                {
                    PCMDataInfo pcmInfo;
                    FileStream  newFile;
                    if (File.Exists(ofd.FileName))
                    {
                        try
                        {
                            newFile = new FileStream(ofd.FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Write);
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show(
                                String.Format("Could not open wave file {0}: {1}", ofd.FileName, err.Message),
                                "Open wave file");
                            return;
                        }
                        try
                        {
                            pcmInfo = PCMDataInfo.ParseRiffWaveHeader(newFile);
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show(
                                String.Format("Invalid wave file {0}: {1}", ofd.FileName, err.Message),
                                "Open wave file");
                            newFile.Close();
                            return;
                        }
                    }
                    else
                    {
                        try
                        {
                            newFile = new FileStream(ofd.FileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Write);
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show(
                                String.Format("Could not open wave file {0}: {1}", ofd.FileName, err.Message),
                                "Open wave file");
                            return;
                        }
                        pcmInfo = new PCMDataInfo();
                        pcmInfo.WriteRiffWaveHeader(newFile);
                    }
                    if (mFile != null)
                    {
                        mPCMInfo.DataLength = (uint)(mFile.Length - mDataStartPosition);
                        FixWaveHeader();
                        mFile.Close();
                    }
                    mFile              = newFile;
                    mPCMInfo           = pcmInfo;
                    mDataStartPosition = (uint)mFile.Position;
                    mFileTextBox.Text  = ofd.FileName;
                    mCurFileTime       = TimeSpan.Zero;
                    UpdateTime();
                    UpdateTransportControls();
                    GotoTimeSlider();
                }
            }
        }