菜鸟教程小白 发表于 2022-12-11 16:49:54

ios - 音频文件未从文档目录播放


                                            <p><p>我在文档目录中有一个音频文件,它没有播放,但我没有收到任何错误或崩溃。我真的被这种情况困住了,引用了很多 SO 链接,但没有一个能解决我的问题。</p>

<pre><code>var myPlayer = AVAudioPlayer()

    let fileManager = NSFileManager.defaultManager()

    let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    if let documentDirectoryURL: NSURL = urls.first {
    print(documentDirectoryURL)// File copied to this directory
    let soundURL = documentDirectoryURL.URLByAppendingPathComponent(&#34;09.mp3&#34;)
      do {
            myPlayer = try AVAudioPlayer(contentsOfURL: soundURL)
            myPlayer.delegate = self
            myPlayer.prepareToPlay()
            myPlayer.play()
      } catch let error as NSError {
            NSLog(&#34;Unresolved error \(error.debugDescription)&#34;)
            // SHOW ALERT OR SOMETHING
      }
    }
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>让我澄清一下;</p>

<p>播放音频文件有两种标准方式:</p>

<p>录制音频,然后使用完成处理程序将其导出到应用程序(文档目录)内的文件中。从那里我们可以从文档目录访问该文件。 </p>

<pre><code>let settings = [
    AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
    AVSampleRateKey: 12000.0,
    AVNumberOfChannelsKey: 1 as NSNumber,
    AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
]

do {
    audioURL = let audioFilename = getDocumentsDirectory().stringByAppendingPathComponent(&#34;recording.m4a&#34;)
let audioURL = NSURL(fileURLWithPath: audioFilename)
    audioRecorder = try AVAudioRecorder(URL: audioURL, settings: settings)
}

class func getDocumentsDirectory() -&gt; String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths
    return documentsDirectory
}
</code></pre>

<p>还有更多你喜欢的实际录音等等。这里有一个教程</p>

<p> <a href="https://www.hackingwithswift.com/example-code/media/how-to-record-audio-using-avaudiorecorder" rel="noreferrer noopener nofollow">https://www.hackingwithswift.com/example-code/media/how-to-record-audio-using-avaudiorecorder</a> </p>

<p>--或--</p>

<p>我们在计算机上有一个音频,您将其传输到 XCode,您可以使用它调用它</p>

<pre><code>myPlayer = try AVAudioPlayer(fileURLWithPath: &#34;09.mp3&#34;)
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 音频文件未从文档目录播放,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/38030199/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/38030199/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 音频文件未从文档目录播放