here is all my codes for play a mp4,the mp4 is playing but no sounds out
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()
}
}
i'm sure it has sounds,because i can hear when play the mp4 using VLC, did i miss something ?
Check your phone is silent mode or not. If it is silent try add code below to viewDidLoad
:
Swift 2.3
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: [])
Swift 3
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
Swift 4.2
try! AVAudioSession.sharedInstance().setCategory(.playback, options: [])
Or just
try! AVAudioSession.sharedInstance().setCategory(.playback)
For Swift 4.2, put following lines in viewDidLoad
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
}
catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
For Swift 5
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
}
catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With