xamarin.ios 录音并播放

来源:互联网 发布:蓝格眼镜软件 编辑:程序博客网 时间:2024/06/05 04:28

【广告】168vpn 翻墙神器。多多支持   

 AVAudioRecorder recorder;

            NSError error = new NSError(new NSString("com.xamarin"), 1);
            NSUrl url;
            NSDictionary settings;

            var audioSession = AVAudioSession.SharedInstance ();
            var err = audioSession.SetCategory (AVAudioSessionCategory.PlayAndRecord);
            if(err != null) {
                Console.WriteLine ("audioSession: {0}", err);
                return  ;
            }
            err = audioSession.SetActive (true);
            if(err != null ){
                Console.WriteLine ("audioSession: {0}", err);
                return  ;
            }


            //Declare string for application temp path and tack on the file extension
             
            string audioFilePath = Path.Combine (Path.GetTempPath (), "bin.wav");

            Console.WriteLine("Audio File Path: " + audioFilePath);

            url = NSUrl.FromFilename(audioFilePath);
            //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
            NSObject[] values = new NSObject[]
            {
                NSNumber.FromFloat (44100.0f), //Sample Rate
                NSNumber.FromInt32 ((int)AudioToolbox.AudioFormatType.LinearPCM), //AVFormat
                NSNumber.FromInt32 (2), //Channels
                NSNumber.FromInt32 (16), //PCMBitDepth
                NSNumber.FromBoolean (false), //IsBigEndianKey
                NSNumber.FromBoolean (false) //IsFloatKey
            };

            //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };

            //Set Settings with the Values and Keys to create the NSDictionary
            settings = NSDictionary.FromObjectsAndKeys (values, keys);

            //Set recorder parameters
            recorder = AVAudioRecorder.Create(url, new AudioSettings(settings), out error);

            //Set Recorder to Prepare To Record
            recorder.PrepareToRecord();
            btn.TouchUpInside +=async (sender, e) => {
                recorder.PrepareToRecord();
                recorder.Record();

            };
             
            btn2.TouchUpInside +=async (sender, e) => {
                recorder.Stop();
                AVAudioPlayer pla=AVAudioPlayer.FromUrl(url);
                pla.Play();
            };
0 0
原创粉丝点击