iOS播放mp3没声音

方式一1:


NSURL * url  = [[NSBundle mainBundle] URLForResource:@"mmusic" withExtension:@".mp3"];

    AVPlayerItem * songItem = [[AVPlayerItem alloc]initWithURL:url];
    self.PlayBgMp3Player = [[AVPlayer alloc]initWithPlayerItem:songItem];

    //AVPlayer * player = [[AVPlayer alloc] initWithURL:url];
    //AVPlayerItem * songItem = player.currentItem;

    [self.PlayBgMp3Player play];

方式2:

NSURL *fileURL = [[NSBundle mainBundle]URLForResource:@"mmusic" withExtension:@"mp3"];
    // 2.创建 AVAudioPlayer 对象
    self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
    // 3.打印歌曲信息
    NSString *msg = [NSString stringWithFormat:@"音频文件声道数:%ld\n 音频文件持续时间:%g",self.audioPlayer.numberOfChannels,self.audioPlayer.duration];
    NSLog(@"%@",msg);
    // 4.设置循环播放
    self.audioPlayer.volume = 1.0;
    self.audioPlayer.numberOfLoops = -1;
    // 5.开始播放
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];


播放不出来:需要在两种方式代码之前,加上:

AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];

并且需要在target->capabilities->Background Modes,对第一个,就是audio,airplay那一个打沟。


你可能感兴趣的:(app苹果iOS类)