我确信自发布此问题以来发生了很多变化,但这是我通过“复制到:”共享选项设法将语音备忘录应用程序中的音频文件导出到我的应用程序的方法。
- 在 XCode 中,在我的目标的 info 面板下,我添加了
com.apple.m4a-audio Document Type 并将 Supports opening documents in place(设置为 YES)添加到 自定义 iOS 目标属性(见下图)
- 在我的
AppDelegate 我实现了application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
就是这样。现在从我设备上的语音备忘录应用程序中,如果我按下备忘录上的“共享”按钮,我会在选项列表中看到“复制到 [我的应用程序]”(可能需要通过最后一个选项“更多”启用它)
这是 Target 的 info 面板中所需更改的图片:
还有一个代码示例,用于在按下“复制到 [您的应用]”后立即在您自己的应用中播放选定的语音备忘录(将在您的 AppDelegate 中实现):
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let engine = AVAudioEngine()
let player = AVAudioPlayerNode()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
guard let copyURL = URL(string: "test.m4a", relativeTo: FileManager.default.temporaryDirectory) else {
return false
}
engine.attach(player)
engine.connect(player, to: engine.mainMixerNode, format: nil)
do {
// Copy voice memo to this app's temp directory
try FileManager.default.copyItem(at: url, to: copyURL)
// Create readable audio file from copied file
let file = try AVAudioFile(forReading: copyURL)
// "Load" the file into the player
player.scheduleFile(file, at: nil, completionHandler: nil)
try AVAudioSession.sharedInstance().setActive(true)
try engine.start()
} catch {
print(error)
return false
}
player.play()
return true
}
}
请注意,此代码仅用于说明语音备忘录的 url 已正确传播到您的应用程序以及如何将文件复制到临时目录。从那里你可能想将它传递给正确的 ViewController。
编辑:更改代码以说明如何复制文件