Пример #1
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            UIImage greenImage = new UIImage("green_button.png").StretchableImage(12, 0);
            UIImage redImage   = new UIImage("red_button.png").StretchableImage(12, 0);

            startButton.SetBackgroundImage(greenImage, UIControlState.Normal);
            startButton.SetBackgroundImage(redImage, UIControlState.Disabled);

            // default output format
            // sample rate of 0 indicates source file sample rate
            outputFormat = AudioFormatType.AppleLossless;
            sampleRate   = 0;

            // can we encode to AAC?
            if (IsAACHardwareEncoderAvailable())
            {
                outputFormatSelector.SetEnabled(true, 0);
            }
            else
            {
                // even though not enabled in IB, this segment will still be enabled
                // if not specifically turned off here which we'll assume is a bug
                outputFormatSelector.SetEnabled(false, 0);
            }

            sourceURL = CFUrl.FromFile("sourcePCM.aif");
            var paths = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User);

            destinationFilePath = paths[0] + "/output.caf";
            destinationURL      = NSUrl.FromFilename(destinationFilePath);

            UpdateFormatInfo(fileInfo, sourceURL);
        }
Пример #2
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var url = CFUrl.FromFile("loop_stereo.aif");

            _player = new ExtAudioBufferPlayer(url);

            // setting audio session
            _slider.ValueChanged += new EventHandler(_slider_ValueChanged);

            _slider.MaxValue = _player.TotalFrames;

            _isTimerAvailable = true;
            _timer            = NSTimer.CreateRepeatingTimer(TimeSpan.FromMilliseconds(100),
                                                             delegate
            {
                if (_isTimerAvailable)
                {
                    long pos               = _player.CurrentPosition;
                    _slider.Value          = pos;
                    _signalLevelLabel.Text = _player.SignalLevel.ToString("0.00E0");
                }
            }
                                                             );

            NSRunLoop.Current.AddTimer(_timer, NSRunLoopMode.Default);
        }
Пример #3
0
        public static ExtAudioFile GetExtAudioFile(NSUrl url, out AudioStreamBasicDescription audioDescription)
        {
            // Notice the following line that we can not pass a NSUrl to a CFUrl
            //ExtAudioFile ext = ExtAudioFile.OpenUrl(url);

            // Basic Descriptions
            AudioStreamBasicDescription fileFormat;
            AudioStreamBasicDescription outputFormat;

            // So now we create a CFUrl
            CFUrl curl = CFUrl.FromFile(url.Path);

            // Open the file
            ExtAudioFile ext = ExtAudioFile.OpenUrl(curl);

            // Get the audio format
            fileFormat = ext.FileDataFormat;

            // Don't know how to handle sounds with more than 2 channels (i.e. stereo)
            // Remember that OpenAL sound effects must be mono to be spatialized anyway.
            if (fileFormat.ChannelsPerFrame > 2)
            {
#if DEBUG
                Console.WriteLine("Unsupported Format: Channel count [0] is greater than stereo.", fileFormat.ChannelsPerFrame);
#endif
                audioDescription = new AudioStreamBasicDescription();
                return(null);
            }

            // The output format must be linear PCM because that's the only type OpenAL knows how to deal with.
            // Set the client format to 16 bit signed integer (native-endian) data because that is the most
            // optimal format on iPhone/iPod Touch hardware.
            // Maintain the channel count and sample rate of the original source format.
            outputFormat                  = new AudioStreamBasicDescription();  // Create our output format description to be converted to
            outputFormat.SampleRate       = fileFormat.SampleRate;              // Preserve the original sample rate
            outputFormat.ChannelsPerFrame = fileFormat.ChannelsPerFrame;        // Preserve the orignal number of channels
            outputFormat.Format           = AudioFormatType.LinearPCM;          // We want Linear PCM

            // IsBigEndian is causing some problems with distorted sounds on MacOSX
//			outputFormat.FormatFlags = AudioFormatFlags.IsBigEndian
//							| AudioFormatFlags.IsPacked
//							| AudioFormatFlags.IsSignedInteger;

            outputFormat.FormatFlags = AudioFormatFlags.IsPacked
                                       | AudioFormatFlags.IsSignedInteger;
            outputFormat.FramesPerPacket = 1;                                 // We know for linear PCM, the definition is 1 frame per packet
            outputFormat.BitsPerChannel  = 16;                                // We know we want 16-bit
            outputFormat.BytesPerPacket  = 2 * outputFormat.ChannelsPerFrame; // We know we are using 16-bit, so 2-bytes per channel per frame
            outputFormat.BytesPerFrame   = 2 * outputFormat.ChannelsPerFrame; // For PCM, since 1 frame is 1 packet, it is the same as mBytesPerPacket

            // Set the desired client (output) data format
            ext.ClientDataFormat = outputFormat;

            // Copy the output format to the audio description that was passed in so the
            // info will be returned to the user.
            audioDescription = outputFormat;

            return(ext);
        }
Пример #4
0
        public void ClientDataFormat()
        {
            var path = NSBundle.MainBundle.PathForResource("1", "caf", "AudioToolbox");

            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path))) {
                var fmt = file.ClientDataFormat;
            }
        }
Пример #5
0
        public void RetainCountFromFile()
        {
            var path = typeof(int).Assembly.Location;

            using (var url = CFUrl.FromFile(path)) {
                Assert.That(TestRuntime.CFGetRetainCount(url.Handle), Is.EqualTo((nint)1), "RetainCount");
            }
        }
Пример #6
0
        public void ClientDataFormat()
        {
            var path = Path.GetFullPath(Path.Combine("AudioToolbox", "1.caf"));

            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path))) {
                var fmt = file.ClientDataFormat;
            }
        }
Пример #7
0
        protected void LoadAudioFile(StreamInfoProvider info)
        {
            // get the path to the file
            string path;

            if (info.IsInternal)
            {
                path = NSBundle.MainBundle.PathForSoundResource(info.Uri);
            }
            else
            {
                // file path is the Uri for user sources
                path = info.Uri;
            }

            using (var url = CFUrl.FromFile(path))
            {
                using (var file = ExtAudioFile.OpenUrl(url))
                {
                    var clientFormat = file.FileDataFormat;
                    clientFormat.FormatFlags       = AudioStreamBasicDescription.AudioFormatFlagsNativeFloat;
                    clientFormat.ChannelsPerFrame  = 1;
                    clientFormat.FramesPerPacket   = 1;
                    clientFormat.BitsPerChannel    = 8 * sizeof(float);
                    clientFormat.BytesPerPacket    =
                        clientFormat.BytesPerFrame = clientFormat.ChannelsPerFrame * sizeof(float);

                    file.ClientDataFormat = clientFormat;

                    double rateRatio = Metronome.SampleRate / clientFormat.SampleRate;

                    var numFrames = file.FileLengthFrames;
                    numFrames = (uint)(numFrames * rateRatio);

                    TotalFrames = numFrames;

                    UInt32 samples  = (uint)(numFrames * clientFormat.ChannelsPerFrame);
                    var    dataSize = (int)(sizeof(uint) * samples);
                    Data = Marshal.AllocHGlobal(dataSize);

                    // set up a AudioBufferList to read data into
                    var bufList = new AudioBuffers(1);
                    bufList[0] = new AudioBuffer
                    {
                        NumberChannels = 1,
                        Data           = Data,
                        DataByteSize   = dataSize
                    };

                    ExtAudioFileError error;
                    file.Read((uint)numFrames, bufList, out error);
                    if (error != ExtAudioFileError.OK)
                    {
                        throw new ApplicationException();
                    }
                }
            }
        }
Пример #8
0
        public void OpenCFUrlTest()
        {
            var path = Path.GetFullPath(Path.Combine("AudioToolbox", "1.caf"));
            ExtAudioFileError err;

            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path), out err)) {
                Assert.IsTrue(err == ExtAudioFileError.OK, "OpenCFUrlTest");
                Assert.IsNotNull(file.AudioFile, "OpenCFUrlTest");
            }
        }
Пример #9
0
 public void ToString_()
 {
     using (CFUrl url = CFUrl.FromFile("/")) {
         string value = TestRuntime.CheckSystemAndSDKVersion(7, 0) ? "file:///" : "file://localhost/";
         Assert.That(url.ToString(), Is.EqualTo(value), "FromFile");
     }
     using (CFUrl url = CFUrl.FromUrlString("/", null)) {
         Assert.That(url.ToString(), Is.EqualTo("/"), "FromUrlString");
     }
 }
Пример #10
0
        public void OpenCFUrlTest()
        {
            var path = NSBundle.MainBundle.PathForResource("1", "caf", "AudioToolbox");
            ExtAudioFileError err;

            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path), out err)) {
                Assert.IsTrue(err == ExtAudioFileError.OK, "OpenCFUrlTest");
                Assert.IsNotNull(file.AudioFile, "OpenCFUrlTest");
            }
        }
Пример #11
0
        public void WrapAudioFileID()
        {
            var path = NSBundle.MainBundle.PathForResource("1", "caf", "AudioToolbox");

            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path))) {
                Assert.IsNotNull(file.AudioFile, "#1");

                ExtAudioFile f2;
                Assert.AreEqual(ExtAudioFileError.OK, ExtAudioFile.WrapAudioFileID(file.AudioFile.Value, true, out f2));
            }
        }
Пример #12
0
        public void WrapAudioFileID()
        {
            var path = Path.GetFullPath(Path.Combine("AudioToolbox", "1.caf"));

            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path))) {
                Assert.IsNotNull(file.AudioFile, "#1");

                ExtAudioFile f2;
                Assert.AreEqual(ExtAudioFileError.OK, ExtAudioFile.WrapAudioFileID(file.AudioFile.Value, true, out f2));
            }
        }
Пример #13
0
        public void ClientDataFormat()
        {
#if MONOMAC
            var path = NSBundle.MainBundle.PathForResource("1", "caf", "AudioToolbox");
#else
            var path = Path.GetFullPath(Path.Combine("AudioToolbox", "1.caf"));
#endif
            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path))) {
                var fmt = file.ClientDataFormat;
            }
        }
Пример #14
0
        static PlatformHardDriveMediaType GetMediaType(string path)
        {
            IntPtr diskHandle    = IntPtr.Zero;
            IntPtr sessionHandle = IntPtr.Zero;
            IntPtr charDictRef   = IntPtr.Zero;
            uint   service       = 0;

            try {
                sessionHandle = DASessionCreate(IntPtr.Zero);

                // This seems to only work for '/'
                var url = CFUrl.FromFile(path);
                diskHandle = DADiskCreateFromVolumePath(IntPtr.Zero, sessionHandle, url.Handle);
                if (diskHandle == IntPtr.Zero)
                {
                    return(PlatformHardDriveMediaType.Unknown);
                }

                service = DADiskCopyIOMedia(diskHandle);

                var cfStr = new CFString("Device Characteristics");
                charDictRef = IORegistryEntrySearchCFProperty(service, "IOService", cfStr.Handle, IntPtr.Zero, 3);

                // CFDictionary owns the object pointed to by resultHandle, so no need to release it
                var resultHandle = CFDictionaryGetValue(charDictRef, new CFString("Medium Type").Handle);
                if (resultHandle == IntPtr.Zero)
                {
                    return(PlatformHardDriveMediaType.Unknown);
                }
                var resultString = (string)NSString.FromHandle(resultHandle);

                if (resultString == "Solid State")
                {
                    return(PlatformHardDriveMediaType.SolidState);
                }
                else if (resultString == "Rotational")
                {
                    return(PlatformHardDriveMediaType.Rotational);
                }
                else
                {
                    return(PlatformHardDriveMediaType.Unknown);
                }
            } finally {
                if (service != 0)
                {
                    IOObjectRelease(service);
                }
                CFRelease(sessionHandle);
                CFRelease(charDictRef);
            }
        }
Пример #15
0
        public void OpenCFUrlTest()
        {
#if MONOMAC
            var path = NSBundle.MainBundle.PathForResource("1", "caf", "AudioToolbox");
#else
            var path = Path.GetFullPath(Path.Combine("AudioToolbox", "1.caf"));
#endif
            ExtAudioFileError err;
            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path), out err)) {
                Assert.IsTrue(err == ExtAudioFileError.OK, "OpenCFUrlTest");
                Assert.IsNotNull(file.AudioFile, "OpenCFUrlTest");
            }
        }
Пример #16
0
        void LoadInstrument(InstrumentInfo info)
        {
            var preset = info.Preset;

            var soundFontPath = NSBundle.MainBundle.PathForResource("ChoriumRevA", "sf2");
            var soundFontUrl  = CFUrl.FromFile(soundFontPath);

            samplerUnit.LoadInstrument(new SamplerInstrumentData(soundFontUrl, InstrumentType.SF2Preset)
            {
                BankLSB  = SamplerInstrumentData.DefaultBankLSB,
                BankMSB  = info.BankMSB,
                PresetID = (byte)preset,
            });
        }
Пример #17
0
        public void WrapAudioFileID()
        {
#if MONOMAC
            var path = NSBundle.MainBundle.PathForResource("1", "caf", "AudioToolbox");
#else
            var path = Path.GetFullPath(Path.Combine("AudioToolbox", "1.caf"));
#endif
            using (var file = ExtAudioFile.OpenUrl(CFUrl.FromFile(path))) {
                Assert.IsNotNull(file.AudioFile, "#1");

                ExtAudioFile f2;
                Assert.AreEqual(ExtAudioFileError.OK, ExtAudioFile.WrapAudioFileID(file.AudioFile.Value, true, out f2));
            }
        }
Пример #18
0
 public static CGPDFDocument FromFile(string str)
 {
     using (var url = CFUrl.FromFile(str)){
         if (url == null)
         {
             return(null);
         }
         IntPtr handle = CGPDFDocumentCreateWithURL(url.Handle);
         if (handle == IntPtr.Zero)
         {
             return(null);
         }
         return(new CGPDFDocument(handle, true));
     }
 }
Пример #19
0
        void loadVirtualInstrument(string instrument, int preset)
        {
            //var soundFontPath = NSBundle.MainBundle.PathForResource("Rhodes EPs Plus-JN1.5", "sf2");
            //var soundFontPath = NSBundle.MainBundle.PathForResource("KBH-Real-Choir-V2.5", "sf2");
            var soundFontPath = NSBundle.MainBundle.PathForResource(instrument, "sf2");

            var soundFontUrl = CFUrl.FromFile(soundFontPath);

            samplerUnit.LoadInstrument(new SamplerInstrumentData(soundFontUrl, InstrumentType.SF2Preset)
            {
                BankLSB  = SamplerInstrumentData.DefaultBankLSB,
                BankMSB  = SamplerInstrumentData.DefaultMelodicBankMSB,
                PresetID = (byte)preset,
            });
        }
Пример #20
0
        public MultichannelMixerController()
        {
            // create the URLs we'll use for source A and B
            var sourceA = NSBundle.MainBundle.PathForResource("GuitarMonoSTP", "aif");
            var sourceB = NSBundle.MainBundle.PathForResource("DrumsMonoSTP", "aif");

            sourceURL = new [] {
                CFUrl.FromFile(sourceA),
                CFUrl.FromFile(sourceB)
            };

            soundBuffer = new SoundBuffer[sourceURL.Length];
            for (int i = 0; i < soundBuffer.Length; ++i)
            {
                soundBuffer [i] = new SoundBuffer();
            }
        }
Пример #21
0
        void RenderAudioAsync()
        {
            CFUrl sourceUrl      = CFUrl.FromFile(NSBundle.MainBundle.PathForResource("composeaudio", "mp3"));
            CFUrl destinationUrl = CFUrl.FromFile(System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), "output.caf"));

            if (busy)
            {
                return;
            }

            busy = true;
            SetCaption("Rendering...");

            var thread = new System.Threading.Thread(() =>
            {
                try {
                    RenderAudio(sourceUrl, destinationUrl);
                } catch (Exception ex) {
                    Console.WriteLine(ex);
                }
                BeginInvokeOnMainThread(() =>
                {
                    SetCaption("Playing...");

                    using (var playUrl = new NSUrl(destinationUrl.Handle)) {
                        player = AVAudioPlayer.FromUrl(playUrl);
                    }

                    player.Play();
                    player.FinishedPlaying += (sender, e) =>
                    {
                        BeginInvokeOnMainThread(() =>
                        {
                            player.Dispose();
                            player = null;
                            SetCaption("Render audio");
                            busy = false;
                        });
                    };
                });
            });

            thread.IsBackground = true;
            thread.Start();
        }
Пример #22
0
        internal SoundEffect(string assetName, bool isMusic)
        {
            // use of CFUrl.FromFile is necessary in case assetName contains spaces (which must be url-encoded)
            audioFile = AudioFile.Open(CFUrl.FromFile(assetName), AudioFilePermission.Read, 0);

            if (audioFile == null)
            {
                throw new Content.ContentLoadException("Could not open sound effect " + assetName);
            }

            description = audioFile.StreamBasicDescription;
            DeriveBufferSize(0.5);
            isVBR = (description.BytesPerPacket == 0 || description.FramesPerPacket == 0);

            if (!isMusic)
            {
                firstInstance = new SoundEffectInstance(this, false);
            }
        }
Пример #23
0
        public void ReadTest()
        {
            var path = Path.GetFullPath(Path.Combine("AudioToolbox", "1.caf"));
            var af   = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF);

            int  len;
            long current = 0;
            long size    = 1024;

            byte [] buffer = new byte [size];
            while ((len = af.Read(current, buffer, 0, buffer.Length, false)) != -1)
            {
                current += len;
            }

            var full_len = new FileInfo(path).Length;
            int header   = 4096;

            Assert.That(header + current == full_len, "#1");
        }
        // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // setting button stat
            _recordingButton.Enabled = true;
            _playBackButton.Enabled  = false;

            // binding event handlers
            _recordingButton.TouchUpInside += new EventHandler(_recordingButton_TouchCancel);
            _playBackButton.TouchUpInside  += new EventHandler(_playBackButton_TouchDown);

            // getting local sound file path
            var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            path = System.IO.Path.Combine(path, "recording.aiff");
            _url = CFUrl.FromFile(path);

            // setting audio session
            AudioSession.Initialize();
            AudioSession.SetActive(true);
        }
Пример #25
0
        public void ToString_()
        {
            using (CFUrl url = CFUrl.FromFile("/")) {
                string value = "file://localhost/";
#if __IOS__
                if (TestRuntime.CheckSystemVersion(PlatformName.iOS, 7, 0))
                {
                    value = "file:///";
                }
#elif __WATCHOS__ || __TVOS__
                value = "file:///";
#elif __MACOS__
                if (TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 9))
                {
                    value = "file:///";
                }
#endif

                Assert.That(url.ToString(), Is.EqualTo(value), "FromFile");
            }
            using (CFUrl url = CFUrl.FromUrlString("/", null)) {
                Assert.That(url.ToString(), Is.EqualTo("/"), "FromUrlString");
            }
        }
Пример #26
0
        public static bool Convert(string input, string output, AudioFormatType targetFormat, AudioFileType containerType, Microsoft.Xna.Framework.Content.Pipeline.Audio.ConversionQuality quality)
        {
            CFUrl           source       = CFUrl.FromFile(input);
            CFUrl           dest         = CFUrl.FromFile(output);
            var             dstFormat    = new AudioStreamBasicDescription();
            var             sourceFile   = AudioFile.Open(source, AudioFilePermission.Read);
            AudioFormatType outputFormat = targetFormat;
            // get the source data format
            var srcFormat        = (AudioStreamBasicDescription)sourceFile.DataFormat;
            var outputSampleRate = 0;

            switch (quality)
            {
            case Microsoft.Xna.Framework.Content.Pipeline.Audio.ConversionQuality.Low:
                outputSampleRate = (int)Math.Max(8000, srcFormat.SampleRate / 2);
                break;

            default:
                outputSampleRate = (int)Math.Max(8000, srcFormat.SampleRate);
                break;
            }

            dstFormat.SampleRate = (outputSampleRate == 0 ? srcFormat.SampleRate : outputSampleRate);             // set sample rate
            if (outputFormat == AudioFormatType.LinearPCM)
            {
                // if the output format is PC create a 16-bit int PCM file format description as an example
                dstFormat.Format           = outputFormat;
                dstFormat.ChannelsPerFrame = srcFormat.ChannelsPerFrame;
                dstFormat.BitsPerChannel   = 16;
                dstFormat.BytesPerPacket   = dstFormat.BytesPerFrame = 2 * dstFormat.ChannelsPerFrame;
                dstFormat.FramesPerPacket  = 1;
                dstFormat.FormatFlags      = AudioFormatFlags.LinearPCMIsPacked | AudioFormatFlags.LinearPCMIsSignedInteger;
            }
            else
            {
                // compressed format - need to set at least format, sample rate and channel fields for kAudioFormatProperty_FormatInfo
                dstFormat.Format           = outputFormat;
                dstFormat.ChannelsPerFrame = (outputFormat == AudioFormatType.iLBC ? 1 : srcFormat.ChannelsPerFrame);                 // for iLBC num channels must be 1

                // use AudioFormat API to fill out the rest of the description
                var fie = AudioStreamBasicDescription.GetFormatInfo(ref dstFormat);
                if (fie != AudioFormatError.None)
                {
                    return(false);
                }
            }

            var converter = AudioConverter.Create(srcFormat, dstFormat);

            converter.InputData += HandleInputData;

            // if the source has a cookie, get it and set it on the Audio Converter
            ReadCookie(sourceFile, converter);

            // get the actual formats back from the Audio Converter
            srcFormat = converter.CurrentInputStreamDescription;
            dstFormat = converter.CurrentOutputStreamDescription;

            // if encoding to AAC set the bitrate to 192k which is a nice value for this demo
            // kAudioConverterEncodeBitRate is a UInt32 value containing the number of bits per second to aim for when encoding data
            if (dstFormat.Format == AudioFormatType.MPEG4AAC)
            {
                uint outputBitRate = 192000;                 // 192k

                // ignore errors as setting may be invalid depending on format specifics such as samplerate
                try {
                    converter.EncodeBitRate = outputBitRate;
                } catch {
                }

                // get it back and print it out
                outputBitRate = converter.EncodeBitRate;
            }

            // create the destination file
            var destinationFile = AudioFile.Create(dest, containerType, dstFormat, AudioFileFlags.EraseFlags);

            // set up source buffers and data proc info struct
            afio            = new AudioFileIO(32768);
            afio.SourceFile = sourceFile;
            afio.SrcFormat  = srcFormat;

            if (srcFormat.BytesPerPacket == 0)
            {
                // if the source format is VBR, we need to get the maximum packet size
                // use kAudioFilePropertyPacketSizeUpperBound which returns the theoretical maximum packet size
                // in the file (without actually scanning the whole file to find the largest packet,
                // as may happen with kAudioFilePropertyMaximumPacketSize)
                afio.SrcSizePerPacket = sourceFile.PacketSizeUpperBound;

                // how many packets can we read for our buffer size?
                afio.NumPacketsPerRead = afio.SrcBufferSize / afio.SrcSizePerPacket;

                // allocate memory for the PacketDescription structures describing the layout of each packet
                afio.PacketDescriptions = new AudioStreamPacketDescription [afio.NumPacketsPerRead];
            }
            else
            {
                // CBR source format
                afio.SrcSizePerPacket  = srcFormat.BytesPerPacket;
                afio.NumPacketsPerRead = afio.SrcBufferSize / afio.SrcSizePerPacket;
                // allocate memory for the PacketDescription structures describing the layout of each packet
                afio.PacketDescriptions = new AudioStreamPacketDescription [afio.NumPacketsPerRead];
            }

            // set up output buffers
            int       outputSizePerPacket = dstFormat.BytesPerPacket;       // this will be non-zero if the format is CBR
            const int theOutputBufSize    = 32768;
            var       outputBuffer        = Marshal.AllocHGlobal(theOutputBufSize);

            AudioStreamPacketDescription[] outputPacketDescriptions = null;

            if (outputSizePerPacket == 0)
            {
                // if the destination format is VBR, we need to get max size per packet from the converter
                outputSizePerPacket = (int)converter.MaximumOutputPacketSize;
            }
            // allocate memory for the PacketDescription structures describing the layout of each packet
            outputPacketDescriptions = new AudioStreamPacketDescription [theOutputBufSize / outputSizePerPacket];
            int numOutputPackets = theOutputBufSize / outputSizePerPacket;

            // if the destination format has a cookie, get it and set it on the output file
            WriteCookie(converter, destinationFile);

            // write destination channel layout
            if (srcFormat.ChannelsPerFrame > 2)
            {
                WriteDestinationChannelLayout(converter, sourceFile, destinationFile);
            }

            long         totalOutputFrames = 0;     // used for debugging
            long         outputFilePos     = 0;
            AudioBuffers fillBufList       = new AudioBuffers(1);
            bool         error             = false;

            // loop to convert data
            while (true)
            {
                // set up output buffer list
                fillBufList [0] = new AudioBuffer()
                {
                    NumberChannels = dstFormat.ChannelsPerFrame,
                    DataByteSize   = theOutputBufSize,
                    Data           = outputBuffer
                };

                // convert data
                int ioOutputDataPackets = numOutputPackets;
                var fe = converter.FillComplexBuffer(ref ioOutputDataPackets, fillBufList, outputPacketDescriptions);
                // if interrupted in the process of the conversion call, we must handle the error appropriately
                if (fe != AudioConverterError.None)
                {
                    error = true;
                    break;
                }

                if (ioOutputDataPackets == 0)
                {
                    // this is the EOF conditon
                    break;
                }

                // write to output file
                var inNumBytes = fillBufList [0].DataByteSize;

                var we = destinationFile.WritePackets(false, inNumBytes, outputPacketDescriptions, outputFilePos, ref ioOutputDataPackets, outputBuffer);
                if (we != 0)
                {
                    error = true;
                    break;
                }

                // advance output file packet position
                outputFilePos += ioOutputDataPackets;

                if (dstFormat.FramesPerPacket != 0)
                {
                    // the format has constant frames per packet
                    totalOutputFrames += (ioOutputDataPackets * dstFormat.FramesPerPacket);
                }
                else
                {
                    // variable frames per packet require doing this for each packet (adding up the number of sample frames of data in each packet)
                    for (var i = 0; i < ioOutputDataPackets; ++i)
                    {
                        totalOutputFrames += outputPacketDescriptions [i].VariableFramesInPacket;
                    }
                }
            }

            Marshal.FreeHGlobal(outputBuffer);

            if (!error)
            {
                // write out any of the leading and trailing frames for compressed formats only
                if (dstFormat.BitsPerChannel == 0)
                {
                    // our output frame count should jive with
                    WritePacketTableInfo(converter, destinationFile);
                }

                // write the cookie again - sometimes codecs will update cookies at the end of a conversion
                WriteCookie(converter, destinationFile);
            }

            converter.Dispose();
            destinationFile.Dispose();
            sourceFile.Dispose();

            return(true);
        }
Пример #27
0
        protected INativeObject GetINativeInstance(Type t)
        {
            var ctor = t.GetConstructor(Type.EmptyTypes);

            if ((ctor != null) && !ctor.IsAbstract)
            {
                return(ctor.Invoke(null) as INativeObject);
            }

            if (!NativeObjectInterfaceType.IsAssignableFrom(t))
            {
                throw new ArgumentException("t");
            }
            switch (t.Name)
            {
            case "CFAllocator":
                return(CFAllocator.SystemDefault);

            case "CFBundle":
                var bundles = CFBundle.GetAll();
                if (bundles.Length > 0)
                {
                    return(bundles [0]);
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
                }

            case "CFNotificationCenter":
                return(CFNotificationCenter.Darwin);

            case "CFReadStream":
            case "CFStream":
                CFReadStream  readStream;
                CFWriteStream writeStream;
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(readStream);

            case "CFWriteStream":
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(writeStream);

            case "CFUrl":
                return(CFUrl.FromFile("/etc"));

            case "CFPropertyList":
                return(CFPropertyList.FromData(NSData.FromString("<string>data</string>")).PropertyList);

            case "DispatchData":
                return(DispatchData.FromByteBuffer(new byte [] { 1, 2, 3, 4 }));

            case "AudioFile":
                var path = Path.GetFullPath("1.caf");
                var af   = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF);
                return(af);

            case "CFHTTPMessage":
                return(CFHTTPMessage.CreateEmpty(false));

            case "CFMutableString":
                return(new CFMutableString("xamarin"));

            case "CGBitmapContext":
                byte[] data = new byte [400];
                using (CGColorSpace space = CGColorSpace.CreateDeviceRGB()) {
                    return(new CGBitmapContext(data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast));
                }

            case "CGContextPDF":
                var filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "/t.pdf";
                using (var url = new NSUrl(filename))
                    return(new CGContextPDF(url));

            case "CGColorConversionInfo":
                var cci = new GColorConversionInfoTriple()
                {
                    Space     = CGColorSpace.CreateGenericRgb(),
                    Intent    = CGColorRenderingIntent.Default,
                    Transform = CGColorConversionInfoTransformType.ApplySpace
                };
                return(new CGColorConversionInfo((NSDictionary)null, cci, cci, cci));

            case "CGDataConsumer":
                using (NSMutableData destData = new NSMutableData()) {
                    return(new CGDataConsumer(destData));
                }

            case "CGDataProvider":
                filename = "xamarin1.png";
                return(new CGDataProvider(filename));

            case "CGFont":
                return(CGFont.CreateWithFontName("Courier New"));

            case "CGPattern":
                return(new CGPattern(
                           new RectangleF(0, 0, 16, 16),
                           CGAffineTransform.MakeIdentity(),
                           16, 16,
                           CGPatternTiling.NoDistortion,
                           true,
                           (cgc) => {}));

            case "CMBufferQueue":
                return(CMBufferQueue.CreateUnsorted(2));

            case "CTFont":
                CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes()
                {
                    FamilyName = "Courier",
                    StyleName  = "Bold",
                    Size       = 16.0f
                };
                using (var fd = new CTFontDescriptor(fda))
                    return(new CTFont(fd, 10));

            case "CTFontCollection":
                return(new CTFontCollection(new CTFontCollectionOptions()));

            case "CTFontDescriptor":
                fda = new CTFontDescriptorAttributes();
                return(new CTFontDescriptor(fda));

            case "CTTextTab":
                return(new CTTextTab(CTTextAlignment.Left, 2));

            case "CTTypesetter":
                return(new CTTypesetter(new NSAttributedString("Hello, world",
                                                               new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CTFrame":
                var framesetter = new CTFramesetter(new NSAttributedString("Hello, world",
                                                                           new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                }));
                var bPath = UIBezierPath.FromRect(new RectangleF(0, 0, 3, 3));
                return(framesetter.GetFrame(new NSRange(0, 0), bPath.CGPath, null));

            case "CTFramesetter":
                return(new CTFramesetter(new NSAttributedString("Hello, world",
                                                                new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CTGlyphInfo":
                return(new CTGlyphInfo("copyright", new CTFont("ArialMY", 24), "Foo"));

            case "CTLine":
                return(new CTLine(new NSAttributedString("Hello, world",
                                                         new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CGImageDestination":
                var storage = new NSMutableData();
                return(CGImageDestination.Create(new CGDataConsumer(storage), "public.png", 1));

            case "CGImageMetadataTag":
                using (NSString name = new NSString("tagName"))
                    using (var value = new NSString("value"))
                        return(new CGImageMetadataTag(CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value));

            case "CGImageSource":
                filename = "xamarin1.png";
                return(CGImageSource.FromUrl(NSUrl.FromFilename(filename)));

            case "SecPolicy":
                return(SecPolicy.CreateSslPolicy(false, null));

            case "SecIdentity":
                using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) {
                    NSDictionary[] array;
                    var            result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array);
                    if (result != SecStatusCode.Success)
                    {
                        throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result));
                    }
                    return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle)));
                }

            case "SecTrust":
                X509Certificate x = new X509Certificate(mail_google_com);
                using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com"))
                    return(new SecTrust(x, policy));

            case "SslContext":
                return(new SslContext(SslProtocolSide.Client, SslConnectionType.Stream));

            case "UIFontFeature":
                return(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers));

            case "NetworkReachability":
                return(new NetworkReachability(IPAddress.Loopback, null));

            case "VTCompressionSession":
            case "VTSession":
                return(VTCompressionSession.Create(1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes)null));

            case "VTFrameSilo":
                return(VTFrameSilo.Create());

            case "VTMultiPassStorage":
                return(VTMultiPassStorage.Create());

            case "CFString":
                return(new CFString("test"));

            case "DispatchBlock":
                return(new DispatchBlock(() => { }));

            case "DispatchQueue":
                return(new DispatchQueue("com.example.subsystem.taskXYZ"));

            case "DispatchGroup":
                return(DispatchGroup.Create());

            case "CGColorSpace":
                return(CGColorSpace.CreateDeviceCmyk());

            case "CGGradient":
                CGColor[] cArray = { UIColor.Black.CGColor, UIColor.Clear.CGColor, UIColor.Blue.CGColor };
                return(new CGGradient(null, cArray));

            case "CGImage":
                filename = "xamarin1.png";
                using (var dp = new CGDataProvider(filename))
                    return(CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default));

            case "CGColor":
                return(UIColor.Black.CGColor);

            case "CMClock":
                return(CMClock.HostTimeClock);

            case "CMTimebase":
                return(new CMTimebase(CMClock.HostTimeClock));

            case "CVPixelBufferPool":
                return(new CVPixelBufferPool(
                           new CVPixelBufferPoolSettings(),
                           new CVPixelBufferAttributes(CVPixelFormatType.CV24RGB, 100, 50)
                           ));

            case "SecCertificate":
                using (var cdata = NSData.FromArray(mail_google_com))
                    return(new SecCertificate(cdata));

            case "SecCertificate2":
                using (var cdata = NSData.FromArray(mail_google_com))
                    return(new SecCertificate2(new SecCertificate(cdata)));

            case "SecTrust2":
                X509Certificate x2 = new X509Certificate(mail_google_com);
                using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com"))
                    return(new SecTrust2(new SecTrust(x2, policy)));

            case "SecIdentity2":
                using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) {
                    NSDictionary[] array;
                    var            result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array);
                    if (result != SecStatusCode.Success)
                    {
                        throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result));
                    }
                    return(new SecIdentity2(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle))));
                }

            case "SecKey":
                SecKey private_key;
                SecKey public_key;
                using (var record = new SecRecord(SecKind.Key)) {
                    record.KeyType       = SecKeyType.RSA;
                    record.KeySizeInBits = 512;                     // it's not a performance test :)
                    SecKey.GenerateKeyPair(record.ToDictionary(), out public_key, out private_key);
                    return(private_key);
                }

            case "SecAccessControl":
                return(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly));

            default:
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
            }
        }
Пример #28
0
 public void FromUrlString_Null()
 {
     CFUrl.FromUrlString(null, CFUrl.FromFile("/"));
 }
Пример #29
0
 public void FromFile_Null()
 {
     CFUrl.FromFile(null);
 }
Пример #30
0
 public void FromUrlString_Null()
 {
     Assert.Throws <ArgumentNullException> (() => CFUrl.FromUrlString(null, CFUrl.FromFile("/")));
 }