这是我的所有代码播放mp4,mp4播放但没有声音
import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var containerView: UIView! var playerLayer:AVPlayerLayer! var player:AVPlayer! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let path = NSBundle.mainBundle().pathForResource("huoguo", ofType: "mp4") let url = NSURL(fileURLWithPath: path!) let asset = AVAsset(URL: url) let playerItem = AVPlayerItem(asset: asset) self.player = AVPlayer(playerItem: playerItem) self.playerLayer = AVPlayerLayer(player: player) self.playerLayer.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width * 9 / 16) self.containerView.layer.addSublayer(playerLayer) //self.playerLayer.player?.volume = 1 self.playerLayer.player?.play() } }
我确定它有声音,因为我可以听到使用VLC播放mp4时,我是否想念一些东西?
检查手机是否处于静音模式.如果它是静音,请尝试将以下代码添加到viewDidLoad
:
斯威夫特2.3
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: [])
斯威夫特3
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
对于Swift 4.2,将以下行放入 viewDidLoad
do { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: []) } catch { print("Setting category to AVAudioSessionCategoryPlayback failed.") }