使用AVplayer在swift3中创建课程

时间:2016-09-23 09:20:35

标签: avplayer

这是代码:

import Foundation
import UIKit
import AVFoundation

class MP3PLAYER {

    var player = AVPlayer()

    func PLAY (){

       player.play()

    }

    init ( url_ : String , autoplay_ : String , player_ : AVPlayer) {

       player = player_

       let url = url_

       let playerItem = AVPlayerItem( url:URL( string:url )! )
        player = AVPlayer(playerItem:playerItem)
        player.rate = 1.0;


        if autoplay_ == "YES" {
        player.play()
            print("autoplay is on")
        }

   }
}

在此代码中,甚至没有错误警告。

简单的玩家不会玩。如果我把代码直接放在viewController中而不是播放器工作......

我在viewController中以这种方式使用class:

<code>
import UIKit
import AVFoundation
class Mp3Stream_example: UIViewController {
    var player = AVPlayer()
    override func viewDidLoad() {
     super.viewDidLoad()
     let STREAM1 = MP3PLAYER(url_: "http://listen.181fm.com:181-soul_128k.mp3" , autoplay_: "YES" , player_ : player )
     STREAM1.player.play()
     //player.play()   
     .....
 </code>

1 个答案:

答案 0 :(得分:1)

您的播放器STREAM1超出范围且正在取消分配,因此没有声音。使其成为类成员变量而不是局部变量。 e.g。

class Mp3Stream_example: UIViewController {
    let STREAM1 = MP3PLAYER(url_: "http://listen.181fm.com:181-soul_128k.mp3" , autoplay_: "YES" , player_ : AVPlayer() )
     ....

P.S。你有额外的AVPlayer个你不需要的东西。