【问题标题】:Can't play local audio mp3 file with AVAudioPlayer无法使用 AVAudioPlayer 播放本地音频 mp3 文件
【发布时间】:2019-05-22 06:10:59
【问题描述】:

我想从 Google 翻译(文本到语音)下载并播放声音。

mp3 文件下载成功。我尝试用 AVAudioPlayer 播放,但模拟器和我的真 iPhone 都没有声音

我使用 XCode 10.2.1、Swift 5。在模拟器 (XSMax) 和 iPhone XSMax 上进行测试

import UIKit
import AVFoundation

class TextToSpeechGoogleTranslate: AVAudioPlayer, AVAudioPlayerDelegate {
  var player: AVAudioPlayer?

  func speak() {
    let fileURL = URL(string: "https://translate.google.com/translate_tts?ie=UTF-8&total=1&idx=0&client=tw-ob&tl=vi&q=Hello" )!

    let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
    let destinationFileUrl = documentsUrl.appendingPathComponent("voice.mp3")

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)

    let request = URLRequest(url:fileURL)

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {

            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
            }

            do {
                try? FileManager.default.removeItem(at: destinationFileUrl)
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                print(destinationFileUrl)

                do {
                    self.player = try AVAudioPlayer(contentsOf: destinationFileUrl)
                    self.player!.delegate = self
                    self.player!.prepareToPlay()
                    self.player!.volume = 1.0
                    self.player!.play()

                }
                catch let error as NSError {
                    print("Error: \(error.localizedDescription)")
                }
                catch {
                    print("AVAudioPlayer init failed")
                }


            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription as Any);
        }
    }
    task.resume()
  }
 }

输出: 成功下载。状态码:200 file:///Users/macbook/Library/Developer/CoreSimulator/Devices/F43F9B03-674C-4EE1-8CAD-01B5145868DE/data/Containers/Data/Application/6D1A3310-386D-4706-9F1E-DFF536B2A43F/Documents/voice.mp3

我在 Finder 中播放了那个文件。没关系。

【问题讨论】:

    标签: swift


    【解决方案1】:

    我刚刚尝试了您的代码,它似乎工作正常。也许问题在于您如何创建TextToSpeechGoogleTranslate 对象并在其上调用speak()。例如,这是我尝试过的:

    class ViewController: UIViewController {
    
        var test: TextToSpeechGoogleTranslate?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            test = TextToSpeechGoogleTranslate()
            test!.speak()
        }
    }
    

    如果这没有帮助,您能否发布一些代码来说明您如何调用此方法?

    【讨论】:

    • 非常感谢。我尝试了你的代码,它就像一个魅力。你能解释一下为什么我的代码失败了:class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let test = TextToSpeechGoogleTranslate() test.speak() } }
    • 很好,很高兴我能帮上忙。您的代码的问题是 test 实例被立即释放。在我的版本中,我保留了一个引用(在viewDidLoad 之外),因此test 将与ViewController 一起被释放,而不是像在你的版本中那样在viewDidLoad 之后!
    【解决方案2】:

    导入 UIKit 导入 AVFoundation

    类 ViewController: UIViewController, AVAudioPlayerDelegate {

    var audioPlayer = TextToSpeechGoogleTranslate()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        audioPlayer.delegate = self
        audioPlayer!.speak()
    }
    

    }

    1) 创建类的实例 2)确认它的代表 3)在您收到数据后调用您的函数 4) 在设备上进行测试时,不要忘记关闭静音模式(提高音量)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多