Using Swift to implement automatic recording device

Source: Internet
Author: User

Basic Introduction

Automatic recording differs from General recording in: Do not press the recording like that-let go of the end, but according to the size of the voice to automatically judge the recording and the point of the stop, and then you can finish recording immediately after the play out. Similar to the effect of talking Tom Cat.

During the initialization phase of the automatic recording, two recording objects need to be created, one that needs to be recorded as a listener and the other for recording at the required moment. The specific process is as follows

Preparatory work

This project is written using Swift, and the member variables are set as follows

If you are not in the Dong Platinum Blog Park See this article please click to view the original text.

    Recording Device    var recoder:avaudiorecorder!    Listener    var monitor:avaudiorecorder!    Player    var player:avaudioplayer!    Timer    var timer:nstimer!    The URL of the recorder    var recordurl:nsurl!    The URL of the listener    var monitorurl:nsurl!

Of course these attributes cannot be directly knocked out need to first introduce a bridging file and import #import <AVFoundation/AVFoundation.h>

Import if there is a problem you can look at this article: How to make OC and swift mixed development

The recorder, listener and timer should be initialized together when the program starts.

Before that, you need to set the quality of the audio, which will use many of the library's own key,Avsampleratekey,avformatidkey,Avnumberofchannelskey, Avencoderaudioqualitykey The values for these keys are generally of type double or int. One by one explanation is not necessary, probably means to save the voice of Hertz (similar to the non-destructive and ordinary QQ music), conversion rate, saved channels, sound quality and so on. Interested can carefully go to the head file to study the study. I checked the highest quality of all the parameters. After the recording, the size is acceptable and the highest quality is available. (But the voice of the hair should be the middle and lower quality, the flow and timeliness of the main)

        Avaudiosession.sharedinstance (). Setcategory (Avaudiosessioncategoryplayandrecord, Error:nil)        var Recodersetting:nsdictionary = Nsdictionary (OBJECTSANDKEYS:14400.0,AVSAMPLERATEKEY,KAUDIOFORMATAPPLEIMA4, Avformatidkey,2,avnumberofchannelskey,0x7f,avencoderaudioqualitykey)

One of these parameters should be the Avaudioquality.max type but Swift does not recognize it, just look inside the constants and fill them in with the 16 binary. The whole thing is to use a dictionary to save all key-value pairs. Then the dictionary is used to instantiate a parameter in the recorder later.

The method of initializing the recorder is as follows, the listener is exactly similar and only needs to be changed to another URL

        Instantiate the recorder        var recordpath = Nstemporarydirectory (). stringByAppendingPathComponent ("RECORD.CAF")        Recordurl = Nsurl.fileurlwithpath (recordpath)        Recoder = Avaudiorecorder (Url:recordurl, settings:recodersetting as [NSObject : Anyobject], Error:nil)
Start recording

The core function is recording, recording the principle is to listen to the size of the sound decibel, set its own critical point to open and close the recording. (Dong Jiahan)

    • If the sound is always small, do not handle it.
    • If the sound is large, first determine whether the recording is now if not, then start recording.
    • If the sound is small, first determine if the recording is now in the recording if you stop recording.
    Func Updatetimer () {        //update measurer        self.monitor.updateMeters ()        //Get talking decibel        var power = Self.monitor.peakPowerForChannel (0);                println ("-----" \ (Power) ")                if (Power > -30) {            if (!self.recoder.recording) {                println (" Start recording ")                Self.recoder.record ()            }        }else {            if (self.recoder.recording) {                println ("End recording")                Self.recoder.stop ()                self.play ()            }                }

The result of the attempt is printed as follows, where the value is the number of decibels listening. Extremely quiet situation is-160 noisy environment is generally-40.

Play sound

Once the recording is complete, you can directly set the sound to play

    Func Play () {        timer.invalidate ()        monitor.stop ()        //delete recording cache        monitor.deleterecording ()        player = Avaudioplayer (Contentsofurl:recordurl, error:nil)        player.delegate = self        player.play ()    }

The timer stop - listener Stop - Delete listener's cache in the figure above is reflected in this code. It is recommended to set up the agent here, because even if it is played once, it is likely to do some extra work after the playback is complete, and this project is expected to be able to loop the recording playback. That is, when the timer is played, the listener restarts the overall process.

Extended operation

The agent abides by the avaudioplayerdelegate. and implements the proxy method, which is called before the method is opened in the proxy method

    Func audioplayerdidfinishplaying (player:avaudioplayer!, successfully flag:bool) {        //re-turn timer        Self.setuptimer ()    }    func Setuptimer () {        Self.monitor.record ()        Self.timer = Nstimer.scheduledtimerwithtimeinterval (0.1, target:self, selector: "Updatetimer", Userinfo:nil, Repeats:true)    }

So that's the end of a complete recording process.

You can also do some special things like talking Tom Cat is not to say what you said, but to do a certain amount of sound processing to say. If you want to do this, you need to turn on sound pre-play before the sound is played, and set some changes to the sound before playing again to achieve the goal. Most properties require a bool value to be opened before they can be modified to operate. For example, replace the play (above) with the following code:

        Allow change speed        Player.enablerate = True        //set speed        player.rate = 2        player.play ()

The value range for this attribute rate is 0.5 to 2.0. The native seems to have found this other change of tone. You should also refer to a third-party library.

If you are not in the Dong Platinum Blog Park See this article please click to view the original text.

Using Swift to implement automatic recording device

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.