【问题标题】:iOS: AVAudioPlayer can it only play one file?iOS:AVAudioPlayer 只能播放一个文件吗?
【发布时间】:2013-07-03 00:44:14
【问题描述】:

只能通过它的 init 方法为 AVAudioPlayer 提供要播放的文件的 URL。 据我了解,如果要播放另一个文件,则需要停止播放旧实例,并使用要播放的新音频文件的 URL 初始化 AVAudioPlayer 的新实例。

但这很困难,因为我有一个导航控制器,当用户离开播放器屏幕时,声音应该继续播放,而且确实如此。但是,当用户从 tableview 中选择要播放的新音频文件时,viewController 和 AVAudioPlayer 的新实例被初始化,我无法阻止旧的播放。我如何让它工作?

【问题讨论】:

  • 您需要在某处跟踪AVAudioPlayer(并且由于您一次只想播放一个文件,因此您只需要跟踪一个 @987654322 @),无论是在单例中,应用程序委托(如建议的答案)中,还是在表格视图本身中。

标签: ios objective-c avaudioplayer avaudiosession


【解决方案1】:

你可以这样做

在您的 v1AppDelegate.h 文件中添加,

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>

@interface v1AppDelegate : UIResponder <UIApplicationDelegate>
{
    AVAudioPlayer *myAudioPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;
@property (strong, nonatomic) UIWindow *window;

@end

现在在你的 v1AppDelegate.m 文件中添加这个

#import "v1AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>

@implementation v1AppDelegate

@synthesize window = _window;
@synthesize myAudioPlayer;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //start a background sound
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Startsound" ofType: @"m4a"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];    
    myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    myAudioPlayer.numberOfLoops = -1; //infinite loop
    [myAudioPlayer play];


    // Override point for customization after application launch.
    return YES;
}

如果您希望在代码中的其他任何位置停止或开始播放此音乐,只需添加此

#import "v1AppDelegate.h"    
- (IBAction)stopMusic
{
    v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate.myAudioPlayer stop];
}

- (IBAction)startMusic
{
    v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate.myAudioPlayer play];
}

【讨论】:

  • 但是 "NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Startsound" ofType: @"m4a"];"现在它只会播放“Startsound”,因为它的 URL 无法更改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多