AvPlayer无法在设备中播放声音

时间:2017-12-13 08:30:16

标签: ios swift swift3 avplayer swift4

我的代码在模拟器中完美运行,它可以毫无问题地流式传输网址。但是当插入实际设备时,它不会播放音频。我的代码如下:

var playerItem: AVPlayerItem?
var player: AVPlayer?

func initPlayer() {
    let url:URL = URL(string:"https://storage.googleapis.com/purelightdatabucket/samples%2F60-Energy%20UPLIFT.mp3")!
    self.playerItem = AVPlayerItem(url: url)
    self.player=AVPlayer(playerItem: self.playerItem!)
    let playerLayer=AVPlayerLayer(player: self.player!)
    playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 50) // actually this player layer is not visible
    self.view.layer.addSublayer(playerLayer)
}

2 个答案:

答案 0 :(得分:4)

将此代码放入 didFinishLaunchingWithOptions

   do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(error)
    }

答案 1 :(得分:0)

您也可以使用它:

您需要添加AVKit& AVFoundation到您的frameworks路径并导入它们:

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let playerItem = AVPlayerItem(url: URL(string: "https://storage.googleapis.com/purelightdatabucket/samples%2F60-Energy%20UPLIFT.mp3")!)
        player = AVPlayer(playerItem: playerItem)
        player.play()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}