SwiftUI

swiftUI AVAudioRecorder,AVAudioP

2021-11-03  本文已影响0人  王勋才
//
//  ContentView.swift
//  Audiorecorder
//
//  Created by wangxuncai on 2021/11/3.
//

import SwiftUI
import AVKit
struct ContentView: View {
    @State var record:Bool = false
    @State var session:AVAudioSession!
    @State var recorder:AVAudioRecorder!
    @State var audio_Play:AVAudioPlayer!
    @State var showAlert = false
    @State var audios:[URL] = []
    var body: some View {
        NavigationView{
            VStack{
                List{
                    ForEach(audios,id:\.self){i in
                        Text(i.relativeString)
                            .onTapGesture {
                                self.playSound(soundURL: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("\(i.relativeString)"))
                            }
                     
                    }
                    .onDelete { IndexSet in
                        audios.remove(atOffsets: IndexSet)
                    }
                   
                  
                }
                .navigationBarItems(trailing: EditButton())
               
                Button(action: {
                    do {
                        if self.record{
                            self.recorder.stop()
                            self.record.toggle()
                            self.getAudios()
                            return
                        }
                        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                        let fileName = url.appendingPathComponent("myrcd\(self.audios.count + 1).m4a")
                        let settings = [
                            AVFormatIDKey:Int(kAudioFormatMPEG4AAC),
                            AVSampleRateKey:12000,
                            AVNumberOfChannelsKey:1,
                            AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
                        ]
                        self.recorder = try AVAudioRecorder(url: fileName, settings: settings)
                        self.recorder.record()
                        self.record.toggle()
                    } catch  {
                        print(error.localizedDescription)
                    }
                    
                }, label: {
                    ZStack{
                        Circle().fill(Color.red).frame(width: 70, height: 70)
                        if record{
                            Circle().stroke(Color.white,lineWidth: 6).frame(width: 85, height: 85)
                        }
                    }
                    
                })
                    .padding(.vertical,25)

            }
           
            .navigationTitle("录音")
        }
        .alert("没有获取到录音权限。请打开录音权限。", isPresented: $showAlert, actions: {
            Button {
                
            } label: {
                Text("确定")
            }

        })
        .onAppear {
            do{
                self.session = AVAudioSession.sharedInstance()
                try self.session.setCategory(.playAndRecord, mode: .default, policy: .default, options:[ .allowBluetoothA2DP,.allowAirPlay,.allowBluetooth])
              //扬声器,蓝牙播放
                self.session.requestRecordPermission { hasPermission in
                    if !hasPermission{
                        self.showAlert.toggle()
                    }else{
                        self.getAudios()
                    }
                }
            }
            catch{
                print(error.localizedDescription)
            }
        }
    }
    //播放
    func playSound(soundURL:URL){
        
        do {
            try audio_Play = AVAudioPlayer(contentsOf: soundURL)
            audio_Play.volume = 1.0
            audio_Play.numberOfLoops = 0
            
            audio_Play.play()
        } catch  {
            print(error.localizedDescription)
        }
        
    }

    func getAudios(){
        do {
            let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let result = try FileManager.default.contentsOfDirectory(at: url,includingPropertiesForKeys: nil,options: .producesRelativePathURLs)
            self.audios.removeAll()
            for i in result{
                self.audios.append(i)
               
            }
        } catch  {
            print(error.localizedDescription)
        }
    }
}




上一篇下一篇

猜你喜欢

热点阅读