无法使用AVAudioPlayer播放本地音频mp3文件

时间:2019-05-22 06:10:59

标签: swift

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

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

我使用XCode 10.2.1,Swift5。在模拟器(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 文件:///Users/macbook/Library/Developer/CoreSimulator/Devices/F43F9B03-674C-4EE1-8CAD-01B5145868DE/data/Containers/Data/Application/6D1A3310-386D-4706-9F1E-DFF536B2A43F/Documents/voice.mp3

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

2 个答案:

答案 0 :(得分:1)

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

class ViewController: UIViewController {

    var test: TextToSpeechGoogleTranslate?

    override func viewDidLoad() {
        super.viewDidLoad()

        test = TextToSpeechGoogleTranslate()
        test!.speak()
    }
}

如果这样做没有帮助,您可以张贴一些代码来显示如何调用此方法吗?

答案 1 :(得分:0)

导入UIKit 导入AVFoundation

ViewController类:UIViewController,AVAudioPlayerDelegate {

var audioPlayer = TextToSpeechGoogleTranslate()

override func viewDidLoad() {
    super.viewDidLoad()

    audioPlayer.delegate = self
    audioPlayer!.speak()
}

}

1)创建您的类的实例 2)确认是委托人 3)收到数据后调用函数 4)从设备进行测试时,不要忘记关闭静音模式(调大音量)