swift 我的应用程序使用AVAudioPlayer录制和播放声音,例如从第五次播放开始,它会给出错误

svmlkihl  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(123)

我使用AVAudioPlayer录制和播放声音,在模拟器中一切正常,但在设备上,例如,从播放第五张唱片开始,它给出错误“打开失败”。(OSStatus错误1685348671。)”
我把音频格式从m4a改成了caf,控制台没有给予出错误,但是下一次播放仍然没有声音。我的代码:

func playByUrl(url: String) {
        let audioFilename = getDocumentsDirectory().appendingPathComponent("\(url).m4a")
     do {
         try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
         try AVAudioSession.sharedInstance().setActive(true)
         player = try AVAudioPlayer(contentsOf: audioFilename, fileTypeHint:     AVFileType.caf.rawValue)
         guard let player = player else { return }
         player.prepareToPlay()
         player.play()
     } catch let error {
         print(error.localizedDescription)
     }
}

字符串

ffvjumwh

ffvjumwh1#

//ask for record permission. IMPORTANT: Make sure you've set `NSMicrophoneUsageDescription` in your Info.plist

var localRecordingURL : URL {
        getDocumentsDirectory().appendingPathComponent("recording.caf")
    }

func requestPermissionForRecording()
{
     AVAudioSession.sharedInstance().requestRecordPermission() { [unowned self] allowed in
        DispatchQueue.main.async {
            if allowed {
                self.canRecordAudio = true
            } else {
                self.canRecordAudio = false
            }
        }
    }
}

字符串
在录制设置用户语音时检查此代码

func recordAudioFile() {
        do {
            //set the audio session so we can record
            try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
            
        } catch {
            print(error)
            self.canRecord = false
            fatalError()
        }
        //this describes the format the that the file will be recorded in
        let settings = [
            AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
            AVSampleRateKey: 12000,
            AVNumberOfChannelsKey: 1,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]
        do {
            //create the recorder, pointing towards the URL from above
            audioRecorder = try AVAudioRecorder(url: localRecordingURL,
                                                settings: settings)
            audioRecorder?.record() //start the recording
            isRecording = true
        } catch {
            print(error)
            isRecording = false
        }
    }


然后运行录音的播放声音

func playRecordedFile() {
        guard let audioFileURL = audioFileURL else {
            return
        }
        do {
            //create a player, again pointing towards the same URL
            self.audioPlayer = try AVAudioPlayer(contentsOf: audioFileURL)
            self.audioPlayer?.play()
        } catch {
            print(error)
        }
    }


我希望它能解决你的问题

相关问题