iOS application development based on Swift: recording and playing sound

The content involved in this article is suitable for use under the SwiftUI architecture. A complete encapsulated class is provided at the end of the article.

Feel free to leave me a message, or write me an email:

[email protected]

[email protected]

1. Declaration

 

First declare the save path of the file and the suffix of the audio file:

public let PATH_DOC = "/Documents";
public let AUDIO_SUFFIX = "m4a";

Then there are some classes related to recording and playback:

//录音器、会话和播放器
public var audioRecorder:AVAudioRecorder!;
public var audioSession:AVAudioSession!;
public var audioPlayer:AVAudioPlayer!;

All three classes exist in AVKit:

import AVKit

2. Authority

Add permission to use the microphone in XCode's Info configuration:

Privacy - Microphone Usage Description


 

 In the code, we need to determine whether the permission has been obtained when creating the AVAudioSession:

//标记是否需要请求麦克风权限
public var requestMicPerssion:Bool = false;

/**
 * 初始化播放器会话并检查权限
 */
func initAudioRecorder() -> Void {
    do{
        self.audioSession = AVAudioSession.sharedInstance()
        try self.audioSession.setCategory(
            .playAndRecord,
            mode: .default,
            policy: .default,
            options:[ .allowBluetoothA2DP,.allowAirPlay,.allowBluetooth]
        );
            
        //请求权限
        self.audioSession.requestRecordPermission { hasPermission in
            if !hasPermission{
                self.requestMicPerssion = true;
            }
            else{
                self.requestMicPerssion = false;
            }
        }
    }
    catch{
        print(error.localizedDescription)
    }    
}

 3. Recording

When using the AVAudioRecorder class for recording, we need to provide this class with a save path for the recording file, which contains the complete file name.

//标记是否开始录音
public var isRecording:Bool = false;
    
//录音文件的文件名
public var audioFileName:String = "";
/**
 * 开始录音
 */
func startRecord() ->Void{
    do {
        //标

Guess you like

Origin blog.csdn.net/freezingxu/article/details/125046159