Я работаю над приложением iOS с использованием Swift, в котором мне нужно воспроизводить аудиофайлы, созданные пользователем. Однако когда дело доходит до загрузки файла, я сталкиваюсь с проблемой при попытке инициализировать AVAudioPlayer с использованием аудио, созданного пользователем, но это работает для аудиоресурсов Bundle.
Вот ошибка. Я получаю:
Не удалось инициализировать AVAudioPlayer: операцию не удалось завершить. (Ошибка OSStatus 1685348671.)
import SwiftUI
import UIKit
import AVFoundation
struct ParentView: UIViewControllerRepresentable {
typealias UIViewControllerType = UIImagePickerController
func makeUIViewController(context: Context) -> UIImagePickerController {
let soundSelectorButtonSize: CGFloat = 50
let soundSelectorButton = UIButton(frame: CGRect(x: 20, y: overlayView.bounds.height - soundSelectorButtonSize - 100, width: soundSelectorButtonSize, height: soundSelectorButtonSize))
if let image = UIImage(systemName: "music.note", withConfiguration: symbolConfigSmall) {
soundSelectorButton.setImage(image, for: .normal)
}
soundSelectorButton.tintColor = .white
soundSelectorButton.backgroundColor = .clear
soundSelectorButton.addTarget(context.coordinator, action: #selector(Coordinator.showSoundSelector), for: .touchUpInside)
let recordButton = UIButton()
recordButton.addTarget(context.coordinator, action: #selector(Coordinator.startRecording), for: .touchDown)
recordButton.addTarget(context.coordinator, action: #selector(Coordinator.stopRecording), for: [.touchUpInside, .touchUpOutside])
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}
class Coordinator: NSObject, AVAudioRecorderDelegate {
var parent: ParentView
var audioRecorder: AVAudioRecorder?
var audioURL: URL?
init(_ parent: CameraView) {
self.parent = parent
super.init()
setupAudioRecorder()
}
func setupAudioRecorder() {
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
let documentsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
audioURL = documentsPath.appendingPathComponent("mySuperCoolApp.m4a")
do {
audioRecorder = try AVAudioRecorder(url: audioURL!, settings: settings)
audioRecorder?.prepareToRecord()
} catch {
print("Error setting up the audio recorder:", error)
}
}
@objc func startRecording(_ sender: UIButton) {
print("Recording started")
audioRecorder?.record()
}
@objc func stopRecording(_ sender: UIButton) {
print("Recording ended")
audioRecorder?.stop()
if FileManager.default.fileExists(atPath: audioURL!.path) {
print("File saved!")
} else {
print("File did not save.")
}
}
@objc func showSoundSelector() {
if let audioURL = audioURL, FileManager.default.fileExists(atPath: audioURL.path) {
print("Custom sound file exists at \(audioURL)")
} else {
print("Custom sound file does not exist.")
}
let soundOptions = ["audio1", "audio2", "audio3", "audio4"]
let alert = UIAlertController(title: "Select Sound", message: nil, preferredStyle: .actionSheet)
let customAction = UIAlertAction(title: "Custom Sound", style: .default) { _ in
self.loadSound(isCustom: true)
}
for option in soundOptions {
let action = UIAlertAction(title: option, style: .default) { _ in
self.loadSound(named: option)
}
alert.addAction(action)
}
if FileManager.default.fileExists(atPath: audioURL!.path) {
alert.addAction(customAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
parent.imagePicker.present(alert, animated: true)
}
func loadSound(named name: String = "Recording", isCustom: Bool = false) {
var sound: URL?
if isCustom { //USER RECORDED AUDIO
if let audioURL = audioURL, FileManager.default.fileExists(atPath: audioURL.path) {
sound = audioURL
print("Custom sound file exists at \(audioURL)")
} else {
print("Custom audio file not found.")
return
}
} else {
if let path = Bundle.main.path(forResource: name, ofType: "m4a") {
sound = URL(fileURLWithPath: path)
} else {
print("Bundled audio file \(name) not found.")
return
}
}
if let soundURL = sound {
do {
print(soundURL)
audioPlayer = try AVAudioPlayer(contentsOf: soundURL) //TODO: Error Occurring here!
audioPlayer?.prepareToPlay()
} catch {
print("Failed to initialize AVAudioPlayer: \(error.localizedDescription)")
}
} else {
print("Sound URL is nil.")
}
}
}
Забавно то, что это сработало, когда я впервые реализовал это. Понятия не имею, что изменилось.
Информационный список требует описания использования.
пробовал изменить тип аудиофайла.
пробовал подготовить звук в нескольких областях.
Я работаю над приложением iOS с использованием Swift, в котором мне нужно воспроизводить аудиофайлы, созданные пользователем. Однако когда дело доходит до загрузки файла, я сталкиваюсь с проблемой при попытке инициализировать AVAudioPlayer с использованием аудио, созданного пользователем, но это работает для аудиоресурсов Bundle. Вот ошибка. Я получаю:
Не удалось инициализировать AVAudioPlayer: операцию не удалось завершить. (Ошибка OSStatus 1685348671.)
@objc func stopRecording(_ sender: UIButton) { print("Recording ended") audioRecorder?.stop() if FileManager.default.fileExists(atPath: audioURL!.path) { print("File saved!") } else { print("File did not save.") } }
@objc func showSoundSelector() { if let audioURL = audioURL, FileManager.default.fileExists(atPath: audioURL.path) { print("Custom sound file exists at \(audioURL)") } else { print("Custom sound file does not exist.") } let soundOptions = ["audio1", "audio2", "audio3", "audio4"] let alert = UIAlertController(title: "Select Sound", message: nil, preferredStyle: .actionSheet)
let customAction = UIAlertAction(title: "Custom Sound", style: .default) { _ in self.loadSound(isCustom: true) }
for option in soundOptions { let action = UIAlertAction(title: option, style: .default) { _ in self.loadSound(named: option) } alert.addAction(action) }
if FileManager.default.fileExists(atPath: audioURL!.path) { alert.addAction(customAction) }
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(cancelAction)
if isCustom { //USER RECORDED AUDIO if let audioURL = audioURL, FileManager.default.fileExists(atPath: audioURL.path) { sound = audioURL print("Custom sound file exists at \(audioURL)") } else { print("Custom audio file not found.") return } } else { if let path = Bundle.main.path(forResource: name, ofType: "m4a") { sound = URL(fileURLWithPath: path) } else { print("Bundled audio file \(name) not found.") return } }
if let soundURL = sound { do { print(soundURL) audioPlayer = try AVAudioPlayer(contentsOf: soundURL) //TODO: Error Occurring here! audioPlayer?.prepareToPlay() } catch { print("Failed to initialize AVAudioPlayer: \(error.localizedDescription)") } } else { print("Sound URL is nil.") } } } [/code] Забавно то, что это сработало, когда я впервые реализовал это. Понятия не имею, что изменилось. Информационный список требует описания использования. пробовал изменить тип аудиофайла. пробовал подготовить звук в нескольких областях.
Я создаю функцию экспорта видео для одного из моих приложений. По сути, видео представляет собой серию одного из шести разных изображений, длится для разных (коротких) продолжительности.
Экспорт работает нормально, когда я экспортирую что -то,...
Версия реагирующего нативного аудио-рекордера
3.6.4
Версия React Native
0.70.3
Платформы, на которых возникла ошибка (IOS или Android или обе?)
Android(эмулятор Android Studio)
Ожидаемое поведение
Возможность прослушивать записанную голосовую...
Я скачал образец аудиозаписи sdl3 с lazyfoo.net по ссылке ниже:
Он работает должным образом, за исключением действия «Воспроизведение» в разделе «ВОСПРОИЗВЕДЕНИЕ».
Следующий код включает основную функцию:
int main( int argc, char* args[] )
{...
public void StartRecording(int micIndex, int speakerIndex)
{
var devices = new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
var selectedDevice = devices ;