簡體   English   中英

AVAudioPlayer無法播放mp3文件

[英]AVAudioPlayer won't play an mp3 file

當我運行應用程序時,當應用程序播放我的MP3文件“ d.mp3”時,我什么也聽不到。 此文件在iTunes中可以正常播放。

我將AVFoundation.framework添加到項目中。 已將文件“ d.mp3”添加到項目。

添加到視圖控制器:

#import <UIKit/UIKit.h>
#import "AVFoundation/AVAudioPlayer.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Play an MP3 file:
    printf("\n Play an MP3 file");
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                         pathForResource:@"d"
                                         ofType:@"mp3"]];
    printf("\n url = %x", (int)url );
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
                                  initWithContentsOfURL:url
                                  error:nil];
    printf("\n audioPlayer = %x", (int)audioPlayer );
    [audioPlayer play];
}

輸出日志:

Play an MP3 file
url = 3ee78eb0
audioPlayer = 3ee77810

非ARC

您必須在播放期間保留它,因為它本身不會保留。 一旦取消分配,它將立即停止播放。

您需要在類中保存AVAudioPlayer實例。 並在停止播放后釋放它。 例如,

#import <AVFoundation/AVFoundation.h>

@interface YourController () <AVAudioPlayerDelegate> {
AVAudioPlayer *_yourPlayer;   // strong reference
}
@end

@implementation YourController

- (IBAction)playAudio:(id)sender
{
  NSURL *url = [[NSBundle mainBundle] URLForResource:@"d" withExtension:@"mp3"];
  _yourPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
  _yourPlayer.delegate = self;
  [_yourPlayer play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (player == _yourPlayer) {
       _yourPlayer = nil;
   }
}

@end

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM