Use swift to implement an automatic recorder and swift to implement the recorder

Source: Internet
Author: User

Use swift to implement an automatic recorder and swift to implement the recorder
Basic Introduction

The difference between automatic recording and general recording is that you do not need to press the recording like that-you can just stop it. Instead, you can automatically judge the recording and the stopped point based on The Voice size, then, the recording can be played immediately after the recording is completed. Similar to reaching the talking Tom cat.

In the initialization phase of automatic recording, two recording objects need to be set up. One needs to always act as the listener, and the other is used to record at the desired time. The specific process is roughly as follows:

// Recorder var recoder: AVAudioRecorder! // Listener var monitor: AVAudioRecorder! // Player var player: AVAudioPlayer! // Timer var timer: nstmer! // Recorder URL var recordURL: NSURL! // Listener URL var monitorURL: NSURL!

Of course, these attributes cannot be directly typed out. You need to first introduce a bridge file and import # import <AVFoundation/AVFoundation. h>

If there is an import problem, you can refer to this article: how to make the Mixed Development of OC and swift

 

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

Before that, you need to set the audio storage quality, which will use keys, AVSampleRateKey, AVFormatIDKey, and AVNumberOfChannelsKey in many libraries, AVEncoderAudioQualityKey values of these keys are generally of the double or int type. There is no need to explain one by one. It probably means to save the Hertz of the sound (similar to the lossless and common QQ music), the conversion rate, the stored sound channel, and the sound quality. If you are interested, you can study it in the header file. I checked the highest quality of all parameters and found that the maximum size is acceptable. (However, the speech should be of medium-and low-quality, with low traffic consumption and high timeliness)

        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 of the AVAudioQuality. Max type, but swift cannot identify it. You can directly check the constants in it and fill them in the hexadecimal format. In general, we first use a dictionary to store all key-value pairs, and then this dictionary will be used as a parameter in the instantiated recorder.

The method for initializing the recorder is as follows. The Listener is completely similar and you only need to change a 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. The recording principle is to listen to the decibel size of the sound. You can set the critical point to enable or disable the recording. (Dong Boran)

  • If the sound remains small, do not process it.
  • If the sound is too loud, determine whether the current recording is in progress. If not, start recording.
  • If the sound is low, first determine whether the current recording is in progress. If the sound is in progress, stop the recording.
Func updateTimer () {// update the surveyors self. monitor. updateMeters () // obtain the 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 is printed as follows, where the value is the number of DB monitored. In extremely quiet situations, the-160 noisy environment is generally about-40.

Playing sound

After the recording is complete, you can directly set the sound to be played immediately.

Func play () {timer. invalidate () monitor. stop () // Delete the recording cache monitor. deleteRecording () player = AVAudioPlayer (contentsOfURL: recordURL, error: nil) player. delegate = self player. play ()}

In the above figure, the timer stop-listener stop-the listener's cache is displayed in this Code. We recommend that you set up a proxy here, because some additional operations may be performed even after a playback is completed, and this project expects loop recording. That is, after the timer is enabled, the listener starts the process again.

Extended operation

The proxy complies with AVAudioPlayerDelegate. And implement the proxy method. Call the previously enabled method in the proxy method.

Func audioPlayerDidFinishPlaying (player: AVAudioPlayer !, Successfully flag: Bool) {// re-enable the timer self. setupTimer ()} func setupTimer () {self. monitor. record () self. timer = NSTimer. scheduledTimerWithTimeInterval (0.1, target: self, selector: "updateTimer", userInfo: nil, repeats: true )}

So far, a complete recording process has ended.

You can also perform some special operations, that is, the talking Tom doesn't say what you said, but does something about the voice. To enable this function, you must enable sound pre-playing before playing the audio, and set some operations to change the sound before playing the audio. Before modifying most attributes, you must open a BOOL value. For example, replace play () with the following code)

// Allow speed change player. enableRate = true // set speed player. rate = 2 player. play ()

The value range of rate is 0.5 to 2.0. Native, like finding this other tone change, should also reference a third-party library.

If you do not see this article in Dong baoran blog, click to view the original article.

 

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.